作為Java開發者,我們每天建立很多物件,但我們通常使用依賴管理系統,比如Spring去建立物件。然而這裏有很多建立物件的方法,我們會在這篇文章中學到。
Java中有5種建立物件的方式,下面給出它們的例子還有它們的位元組碼
使用new關鍵字 | } → 呼叫了建構函式 |
使用Class類的newInstance方法 | } → 呼叫了建構函式 |
使用Constructor類的newInstance方法 | } → 呼叫了建構函式 |
使用clone方法 | } → 沒有呼叫建構函式 |
使用反序列化 | } → 沒有呼叫建構函式 |
如果你執行了末尾的的程式,你會發現方法1,2,3用建構函式建立物件,方法4,5沒有呼叫建構函式。
這是最常見也是最簡單的建立物件的方式了。通過這種方式,我們可以呼叫任意的建構函式(無參的和帶引數的)。
java; gutter: false; first-line: 1">Employee emp1 = new Employee();
java; gutter: false; first-line: 1">0: new #19 // class org/programming/mitra/exercises/Employee 3: dup 4: invokespecial #21 // Method org/programming/mitra/exercises/Employee."":()V
我們也可以使用Class類的newInstance方法建立物件。這個newInstance方法呼叫無參的建構函式建立物件。
我們可以通過下面方式呼叫newInstance方法建立物件:
Employee emp2 = (Employee) Class.forName("org.programming.mitra.exercises.Employee").newInstance();
或者
java; gutter: false; first-line: 1">Employee emp2 = Employee.class.newInstance();
java; gutter: false; first-line: 1">51: invokevirtual #70 // Method java/lang/Class.newInstance:()Ljava/lang/Object;
和Class類的newInstance方法很像, java.lang.reflect.Constructor類裡也有一個newInstance方法可以建立物件。我們可以通過這個newInstance方法呼叫有引數的和私有的建構函式。
java; gutter: false; first-line: 1">Constructor<Employee> constructor = Employee.class.getConstructor(); Employee emp3 = constructor.newInstance();
java; gutter: false; first-line: 1">111: invokevirtual #80 // Method java/lang/reflect/Constructor.newInstance:([Ljava/lang/Object;)Ljava/lang/Object;
這兩種newInstance方法就是大家所說的反射。事實上Class的newInstance方法內部呼叫Constructor的newInstance方法。這也是眾多框架,如Spring、Hibernate、Struts等使用後者的原因。想了解這兩個newInstance方法的區別,請看這篇java-with-example.html" target="_blank">Creating objects through Reflection in Java with Example.
無論何時我們呼叫一個物件的clone方法,jvm就會建立一個新的物件,將前面物件的內容全部拷貝進去。用clone方法建立物件並不會呼叫任何建構函式。
要使用clone方法,我們需要先實現Cloneable介面並實現其定義的clone方法。
java; gutter: false; first-line: 1">Employee emp4 = (Employee) emp3.clone();
java; gutter: false; first-line: 1">162: invokevirtual #87 // Method org/programming/mitra/exercises/Employee.clone ()Ljava/lang/Object;
當我們序列化和反序列化一個物件,jvm會給我們建立一個單獨的物件。在反序列化時,jvm建立物件並不會呼叫任何建構函式。
爲了反序列化一個物件,我們需要讓我們的類實現Serializable介面
java; gutter: false; first-line: 1">ObjectInputStream in = new ObjectInputStream(new FileInputStream("data.obj")); Employee emp5 = (Employee) in.readObject();
java; gutter: false; first-line: 1">261: invokevirtual #118 // Method java/io/ObjectInputStream.readObject:()Ljava/lang/Object;
我們從上面的位元組碼片段可以看到,除了第1個方法,其他4個方法全都轉變為invokevirtual(建立物件的直接方法),第一個方法轉變為兩個呼叫,new和invokespecial(建構函式呼叫)。
讓我們看一看為下面這個Employee類建立物件:
java; gutter: false; first-line: 1">class Employee implements Cloneable, Serializable { private static final long serialVersionUID = 1L; private String name; public Employee() { System.out.println("Employee Constructor Called..."); } public String getName() { return name; } public void setName(String name) { this.name = name; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((name == null) ? 0 : name.hashCode()); return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; Employee other = (Employee) obj; if (name == null) { if (other.name != null) return false; } else if (!name.equals(other.name)) return false; return true; } @Override public String toString() { return "Employee [name=" + name + "]"; } @Override public Object clone() { Object obj = null; try { obj = super.clone(); } catch (CloneNotSupportedException e) { e.printStackTrace(); } return obj; } }
下面的Java程式中,我們將用5種方式建立Employee物件。你可以從GitHub找到這些程式碼。
java; gutter: false; first-line: 1" data-find="_1">public class ObjectCreation { public static void main(String... args) throws Exception { // By using new keyword Employee emp1 = new Employee(); emp1.setName("Naresh"); System.out.println(emp1 + ", hashcode : " + emp1.hashCode()); // By using Class class's newInstance() method Employee emp2 = (Employee) Class.forName("org.programming.mitra.exercises.Employee") .newInstance(); // Or we can simply do this // Employee emp2 = Employee.class.newInstance(); emp2.setName("Rishi"); System.out.println(emp2 + ", hashcode : " + emp2.hashCode()); // By using Constructor class's newInstance() method Constructor<Employee> constructor = Employee.class.getConstructor(); Employee emp3 = constructor.newInstance(); emp3.setName("Yogesh"); System.out.println(emp3 + ", hashcode : " + emp3.hashCode()); // By using clone() method Employee emp4 = (Employee) emp3.clone(); emp4.setName("Atul"); System.out.println(emp4 + ", hashcode : " + emp4.hashCode()); // By using Deserialization // Serialization ObjectOutputStream out = new ObjectOutputStream(new FileOutputStream("data.obj")); out.writeObject(emp4); out.close(); //Deserialization ObjectInputStream in = new ObjectInputStream(new FileInputStream("data.obj")); Employee emp5 = (Employee) in.readObject(); in.close(); emp5.setName("Akash"); System.out.println(emp5 + ", hashcode : " + emp5.hashCode()); } }
程式會輸出:
java; gutter: false; first-line: 1">Employee Constructor Called... Employee [name=Naresh], hashcode : -1968815046 Employee Constructor Called... Employee [name=Rishi], hashcode : 78970652 Employee Constructor Called... Employee [name=Yogesh], hashcode : -1641292792 Employee [name=Atul], hashcode : 2051657 Employee [name=Akash], hashcode : 63313419 本文來自碼農網