首頁 > Java > java教程 > 主體

Java中創建物件的5種方式

黄舟
發布: 2017-02-06 16:05:34
原創
1056 人瀏覽過

身為Java開發者,我們每天都會創建很多對象,但我們通常使用依賴管理系統,例如Spring去創建對象。然而這裡有很多創建物件的方法,我們會在這篇文章中學到。


Java中有5種創建物件的方式,下面給出它們的例子還有它們的字節碼

Java中創建物件的5種方式

如果你運行了末尾的程序,你會發現方法1,2, 3用建構函式建立對象,方法4,5沒有呼叫建構函式。

1、使用new關鍵字

這是最常見也是最簡單的創建物件的方式了。透過這種方式,我們可以呼叫任意的建構子(無參的和帶參數的)。

Employee emp1 = new Employee();
登入後複製
0: new           #19          // class org/programming/mitra/exercises/Employee
3: dup   
4: 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.g.一個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方法內部呼叫Constructor的newInstance方法。這也是眾多框架,如Spring、Hibernate、Struts等使用後者的原因。

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&#39;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&#39;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());   
    }   
}
登入後複製

程式會輸出:

public class ObjectCreation {   
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
登入後複製

以上就是Java中創建物件的5種方式的內容,更多相關內容請關注PHP中文網(www.php.cn)!


相關標籤:
來源:php.cn
本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
最新問題
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板
關於我們 免責聲明 Sitemap
PHP中文網:公益線上PHP培訓,幫助PHP學習者快速成長!