Java創建對象的幾種方法
1.使用new關鍵字
Person person=new Person();
2.使用Class類的newInstance方法
a) Person ps=(Person) Class.forName("com.springioc.myioc.Person").newInstance();
需要捕獲ClassNotFoundException, IllegalAccessException, InstantiationException異常
b) Person ps2=Person.class.newInstance();
需要捕獲IllegalAccessException, InstantiationException異常
3.使用Constructor類的newInstance方法
a) Constructor<Person> constructor=Person.class.getConstructor();
需要捕獲NoSuchMethodException
Person person=constructor.newInstance();
需要捕獲IllegalAccessException, InvocationTargetException, InstantiationException異常
以上兩種newInstance方法是通過反射來實現的
4.使用clone方法
clone是object的方法,當我們調用一個對象的clone方法,jvm就會創建一個新的對象,將前面對象的內容全部拷貝進去。用clone方法創建對象並不會調用任何構造函數
要使用clone方法,需要先實現Cloneable接口並實現其定義的clone方法
Person person=new Person();
Person pes=(Person).person.clone();
5.使用反序列化
當我們序列化和反序列化一個對象,jvm會給我們創建一個單獨的對象,在反序列化時,jvm創建對象並不會調用任何構造函數
反序列化一個對象,需要讓類實現Serializable接口
Person person=new Person();
person.setName("張三");
person.setPassword("123456789");
ObjectOutputStream out=new ObjectOutputStream(new FileOutputStream("obj.txt"));
out.writeObject(person);
out.close();
ObjectInputStream in=new ObjectInputStream(new FileInputStream("obj.txt"));
Person person1=(Person)in.readObject();
in.close();
System.out.println(person1.getName()+person1.getPassword());
Java創建對象的幾種方法