一、使用new關(guān)鍵字
- 這是我們最常見的也是最簡單的創(chuàng)建對象的方式,通過這種方式我們還可以調(diào)用任意的構(gòu)造函數(shù)(無參的和有參的)。
例如:
User user = new User();
二、使用反射機制
- 運用反射手段,調(diào)用Java.lang.Class或者java.lang.reflect.Constructor類的newInstance()實例方法。
使用class類的newInstance方法
//創(chuàng)建方法1
User user = (User)Class.forName("根路徑.User").newInstance();
//創(chuàng)建方法2(用這個最好)
User user = User.class.newInstance();
使用Constructor類的newInstance方法
和Class類的newInstance方法很像, java.lang.reflect.Constructor類里也有一個newInstance方法可以創(chuàng)建對象。我們可以通過這個newInstance方法調(diào)用有參數(shù)的和私有的構(gòu)造函數(shù)。
Constructor<User> constructor = User.class.getConstructor();
User user = constructor.newInstance();
三、使用clone方法
- 無論何時我們調(diào)用一個對象的clone方法,jvm就會創(chuàng)建一個新的對象,將前面對象的內(nèi)容全部拷貝進(jìn)去。用clone方法創(chuàng)建對象并不會調(diào)用任何構(gòu)造函數(shù)。
要使用clone方法,我們需要先實現(xiàn)Cloneable接口并實現(xiàn)其定義的clone方法。
public class CloneTest implements Cloneable{
private String name;
private int age;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public CloneTest(String name, int age) {
super();
this.name = name;
this.age = age;
}
public static void main(String[] args) {
try {
CloneTest cloneTest = new CloneTest("wangql",18);
CloneTest copyClone = (CloneTest) cloneTest.clone();
System.out.println("newclone:"+cloneTest.getName());
System.out.println("copyClone:"+copyClone.getName());
} catch (CloneNotSupportedException e) {
e.printStackTrace();
}
}
}
執(zhí)行
newclone:wangql
copyClone:wangql
四、使用反序列化
當(dāng)我們序列化和反序列化一個對象,jvm會給我們創(chuàng)建一個單獨的對象。在反序列化時,jvm創(chuàng)建對象并不會調(diào)用任何構(gòu)造函數(shù)。
為了反序列化一個對象,我們需要讓我們的類實現(xiàn)Serializable接口。
學(xué)習(xí)鏈接