java中建立對象的五種方法

來源:互聯網
上載者:User

標籤:ide   ash   struct   ack   object   原因   反序   logs   rac   

用最簡單的描述來區分new關鍵字和newInstance()方法的區別:
newInstance: 弱類型。低效率。只能調用無參構造。
new: 強型別。相對高效。能調用任何public構造。

newInstance( )是一個方法,而new是一個關鍵字,其次,Class下的newInstance()的使用有局限,因為它產生對象只能調用無參的建構函式,而使用new關鍵字產生對象沒有這個限制。
Class.forName("")返回的是類
Class.forName("").newInstance()返回的是object

 

 

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

Java中有5種建立對象的方式,下面給出它們的例子還有它們的位元組碼:

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

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

1.使用new關鍵字

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

<span style="color: #ff0000;">Employee emp1 = new Employee();</span>
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();

 

 

3.使用Constructor類的newInstance方法

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

Constructor<Employee> constructor = Employee.class.getConstructor();

Employee emp3 = constructor.newInstance();  

  這兩種newInstance方法就是大家所說的反射。事實上Class的newInstance方法內部調用Constructor的newInstance方法。這也是眾多架構,如Spring、Hibernate、Struts等使用後者的原因。

4.使用clone方法

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

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

Employee emp4 = (Employee) emp3.clone();

   5.使用還原序列化

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

ObjectInputStream in = new ObjectInputStream(new FileInputStream("data.obj"));Employee emp5 = (Employee) in.readObject();

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

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

 1 class Employee implements Cloneable, Serializable { 2     private static final long serialVersionUID = 1L; 3     private String name; 4     public Employee() { 5         System.out.println("Employee Constructor Called..."); 6     } 7     public String getName() { 8         return name; 9     }10     public void setName(String name) {11         this.name = name;12     }13     @Override14     public int hashCode() {15         final int prime = 31;16         int result = 1;17         result = prime * result + ((name == null) ? 0 : name.hashCode());18         return result;19     }20     @Override21     public boolean equals(Object obj) {22         if (this == obj)23             return true;24         if (obj == null)25             return false;26         if (getClass() != obj.getClass())27             return false;28         Employee other = (Employee) obj;29         if (name == null) {30             if (other.name != null)31                 return false;32         } else if (!name.equals(other.name))33             return false;34         return true;35     }36     @Override37     public String toString() {38         return "Employee [name=" + name + "]";39     }40     @Override41     public Object clone() {42         Object obj = null;43         try {44             obj = super.clone();45         } catch (CloneNotSupportedException e) {46             e.printStackTrace();47         }48         return obj;49     }50 }

 

 

  下面的Java程式中,我們將用5種方式建立Employee對象。

 1 public class ObjectCreation { 2     public static void main(String... args) throws Exception { 3         // By using new keyword 4         Employee emp1 = new Employee(); 5         emp1.setName("Naresh"); 6         System.out.println(emp1 + ", hashcode : " + emp1.hashCode()); 7         // By using Class class‘s newInstance() method 8         Employee emp2 = (Employee) Class.forName("org.programming.mitra.exercises.Employee") 9                                .newInstance();10         // Or we can simply do this11         // Employee emp2 = Employee.class.newInstance();12         emp2.setName("Rishi");13         System.out.println(emp2 + ", hashcode : " + emp2.hashCode());14         // By using Constructor class‘s newInstance() method15         Constructor<Employee> constructor = Employee.class.getConstructor();16         Employee emp3 = constructor.newInstance();17         emp3.setName("Yogesh");18         System.out.println(emp3 + ", hashcode : " + emp3.hashCode());19         // By using clone() method20         Employee emp4 = (Employee) emp3.clone();21         emp4.setName("Atul");22         System.out.println(emp4 + ", hashcode : " + emp4.hashCode());23         // By using Deserialization24         // Serialization25         ObjectOutputStream out = new ObjectOutputStream(new FileOutputStream("data.obj"));26         out.writeObject(emp4);27         out.close();28         //Deserialization29         ObjectInputStream in = new ObjectInputStream(new FileInputStream("data.obj"));30         Employee emp5 = (Employee) in.readObject();31         in.close();32         emp5.setName("Akash");33         System.out.println(emp5 + ", hashcode : " + emp5.hashCode());34     }35 }

 

 

  程式會輸出:

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個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: 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.