Java中建立對象的5種方式

來源:互聯網
上載者:User

標籤:定義   ring   target   not   拷貝   getname   tac   using   函數   

使用new關鍵字 } → 調用了建構函式
使用Class類的newInstance方法 } → 調用了建構函式
使用Constructor類的newInstance方法 } → 調用了建構函式
使用clone方法 } → 沒有調用建構函式
使用還原序列化 } → 沒有調用建構函式

如果你運行了末尾的的程式,你會探索方法1,2,3用建構函式建立對象,方法4,5沒有調用建構函式。

1.使用new關鍵字

這是最常見也是最簡單的建立對象的方式了。通過這種方式,我們可以調用任意的建構函式(無參的和帶參數的)。

Employee emp1 = new Employee();0: new           #19          // class org/programming/mitra/exercises/Employee3: dup4: invokespecial #21          // Method org/programming/mitra/exercises/Employee."":()V
2.使用Class類的newInstance方法

我們也可以使用Class類的newInstance方法建立對象。這個newInstance方法調用無參的建構函式建立對象。

我們可以通過下面方式調用newInstance方法建立對象:

Employee emp2 = (Employee) Class.forName("org.programming.mitra.exercises.Employee").newInstance();或者Employee emp2 = Employee.class.newInstance();51: invokevirtual    #70    // Method java/lang/Class.newInstance:()Ljava/lang/Object;
3.使用Constructor類的newInstance方法

和Class類的newInstance方法很像, java.lang.reflect.Constructor類裡也有一個newInstance方法可以建立對象。我們可以通過這個newInstance方法調用有參數的和私人的建構函式。

Constructor<Employee> constructor = Employee.class.getConstructor();Employee emp3 = constructor.newInstance();111: invokevirtual  #80  // Method java/lang/reflect/Constructor.newInstance:([Ljava/lang/Object;)Ljava/lang/Object;

這兩種newInstance方法就是大家所說的反射。事實上Class的newInstance方法內部調用Constructor的newInstance方法。這也是眾多架構,如Spring、Hibernate、Struts等使用後者的原因。想瞭解這兩個newInstance方法的區別,請看這篇Creating objects through Reflection in Java with Example.

4.使用clone方法

無論何時我們調用一個對象的clone方法,jvm就會建立一個新的對象,將前面對象的內容全部拷貝進去。用clone方法建立對象並不會調用任何建構函式。

要使用clone方法,我們需要先實現Cloneable介面並實現其定義的clone方法。

Employee emp4 = (Employee) emp3.clone();162: invokevirtual #87  // Method org/programming/mitra/exercises/Employee.clone ()Ljava/lang/Object;
5.使用還原序列化

當我們序列化和還原序列化一個對象,jvm會給我們建立一個單獨的對象。在還原序列化時,jvm建立對象並不會調用任何建構函式。
為了還原序列化一個對象,我們需要讓我們的類實現Serializable介面

ObjectInputStream in = new ObjectInputStream(new FileInputStream("data.obj"));Employee emp5 = (Employee) in.readObject();261: invokevirtual  #118   // Method java/io/ObjectInputStream.readObject:()Ljava/lang/Object;

我們從上面的位元組碼片段可以看到,除了第1個方法,其他4個方法全都轉變為invokevirtual(建立對象的直接方法),第一個方法轉變為兩個調用,new和invokespecial(建構函式調用)。

例子

讓我們看一看為下面這個Employee類建立對象:

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找到這些代碼。

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());    }}

程式會輸出:

Employee Constructor Called...Employee [name=Naresh], hashcode : -1968815046Employee Constructor Called...Employee [name=Rishi], hashcode : 78970652Employee Constructor Called...Employee [name=Yogesh], hashcode : -1641292792Employee [name=Atul], hashcode : 2051657Employee [name=Akash], hashcode : 63313419

Java中建立對象的5種方式

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.