Java中五種不同方法的創(chuàng)建對象
前言
作為Java開發(fā)者,我們每天都會創(chuàng)建大量的對象,但是,我們總是使用管理依賴系統(tǒng)(如Spring框架)來創(chuàng)建這些對象。其實還有其他方法可以創(chuàng)建對象,在接下來的文章中我會進行詳細介紹。
1.使用new關(guān)鍵字
這是最常見的創(chuàng)建對象的方法,并且也非常簡單。通過使用這種方法我們可以調(diào)用任何我們需要調(diào)用的構(gòu)造函數(shù)。
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方法來創(chuàng)建對象。此newInstance方法調(diào)用無參構(gòu)造函數(shù)以創(chuàng)建對象。
我們可以通過newInstance() 用以下方式創(chuàng)建對象:
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.使用構(gòu)造函數(shù)類的 newInstance方法
與使用class類的newInstance
方法相似,java.lang.reflect.Constructor
類中有一個可以用來創(chuàng)建對象的newInstance()
函數(shù)方法。通過使用這個newInstance
方法我們也可以調(diào)用參數(shù)化構(gòu)造函數(shù)和私有構(gòu)造函數(shù)。
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()
方法被認為是創(chuàng)建對象的反射手段。實際上,內(nèi)部類的newInstance()
方法使用構(gòu)造函數(shù)類的 newInstance()
方法。這就是為什么后者是首選并且使用不同的框架如Spring, Hibernate, Struts
等。
4.使用clone方法
實際上無論何時我們調(diào)用clone
方法,JAVA虛擬機都為我們創(chuàng)建了一個新的對象并且復(fù)制了之前對象的內(nèi)容到這個新的對象中。使用 clone
方法創(chuàng)建對象不會調(diào)用任何構(gòu)造函數(shù)。
為了在對象中使用clone()
方法,我們需要在其中實現(xiàn)可克隆類型并定義clone方法。
Employee emp4 = (Employee) emp3.clone(); 162: invokevirtual #87 // Method org/programming/mitra/exercises/Employee.clone ()Ljava/lang/Object;
5.使用反序列化
無論何時我們對一個對象進行序列化和反序列化,JAVA虛擬機都會為我們創(chuàng)建一個單獨的對象。在反序列化中,JAVA虛擬機不會使用任何構(gòu)造函數(shù)來創(chuàng)建對象。
對一個對象進行序列化需要我們在類中實現(xiàn)可序列化的接口。
ObjectInputStream in = new ObjectInputStream(new FileInputStream("data.obj")); Employee emp5 = (Employee) in.readObject(); 261: invokevirtual #118 // Method java/io/ObjectInputStream.readObject:()Ljava/lang/Object;
正如我們在以上的字節(jié)代碼片段中所看到的,除第一種被轉(zhuǎn)換為一個新的函數(shù)和一個 invokespecial
指令以外,其它4種方法都被調(diào)用并轉(zhuǎn)換為invokevirtual
。
示例
讓我們來看看準備創(chuàng)建對象的 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種方式來創(chuàng)建 Employee
對象。
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()); } }
此程序輸出結(jié)果如下:
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
以上內(nèi)容是關(guān)于java創(chuàng)建對象的5種不同方法,希望給大家學習java時有所幫助。也謝謝大家對腳本之家的支持。
相關(guān)文章
SpringBoot中的WebSocketSession原理詳解
這篇文章主要介紹了SpringBoot中的WebSocketSession原理詳解,傳統(tǒng)的?HTTP?協(xié)議是無法支持實時通信的,因為它是一種無狀態(tài)協(xié)議,每次請求都是獨立的,無法保持連接。為了解決這個問題,WebSocket?協(xié)議被引入,需要的朋友可以參考下2023-07-07淺析Java 數(shù)據(jù)結(jié)構(gòu)常用接口與類
本篇文章主要介紹了Java中的數(shù)據(jù)結(jié)構(gòu),Java工具包提供了強大的數(shù)據(jù)結(jié)構(gòu)。需要的朋友可以參考下2017-04-04SpringAOP+RabbitMQ+WebSocket實戰(zhàn)詳解
這篇文章主要介紹了SpringAOP+RabbitMQ+WebSocket實戰(zhàn)詳解,小編覺得挺不錯的,現(xiàn)在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧2018-11-11Java中final,finally,finalize?有什么區(qū)別
這篇文章主要給大家分享的是?Java中final,finally,finalize?到底有什么區(qū)別,文章圍繞final,finally,finalize的相關(guān)資料展開詳細內(nèi)容,具有一定的參考的價值,需要的朋友可以參考一下2021-11-11淺談SpringSecurity注解與AOP切面執(zhí)行順序
這篇文章主要介紹了淺談SpringSecurity注解與AOP切面執(zhí)行順序,引入Spring Security后,在Controller的方法中會出現(xiàn)Spring Security的方法注解與AOP同時存在的問題,這是就會設(shè)計順序問題,需要的朋友可以參考下2023-10-10