今天來聊一聊在Java創建對象的幾種方法。在項目裏面,可能你經常使用new創建對象,或者就是把創建對象的事情交給框架(比如spring)。那麼,除了new以外,你還知道幾種創建對象的方法?下面來看看這6種創建對象的方法:
- 使用new關鍵字
- Class對象的newInstance()方法
- 構造函數對象的newInstance()方法
- 對象反序列化
- Object對象的clone()方法
- 繼續往下看,最後揭曉
1.使用new關鍵字
這是最常用也最簡單的方式,看看下面這個例子就知道了。
public class Test { private String name; public Test() { } public Test(String name) { this.name = name; } public String getName() { return name; } public void setName(String name) { this.name = name; } public static void main(String[] args) { Test t1 = new Test(); Test t2 = new Test("張三"); } }
2.Class對象的newInstance()方法
還是上面的Test對象,首先我們通過Class.forName()動態的加載類的Class對象,然後通過newInstance()方法獲得Test類的對象
public static void main(String[] args) throws Exception { String className = "org.b3log.solo.util.Test"; Class clasz = Class.forName(className); Test t = (Test) clasz.newInstance(); }
3.構造函數對象的newInstance()方法
類Constructor也有newInstance方法,這一點和Class有點像。從它的名字可以看出它與Class的不同,Class是通過類來創建對象,而Constructor則是通過構造器。我們依然使用第一個例子中的Test類。
public static void main(String[] args) throws Exception { Constructor<Test> constructor; try { constructor = Test.class.getConstructor(); Test t = constructor.newInstance(); } catch (InstantiationException | IllegalAccessException | IllegalArgumentException | InvocationTargetException | NoSuchMethodException | SecurityException e) { e.printStackTrace(); } }
4.對象反序列化
使用反序列化來獲得類的對象,那麼這裏必然要用到序列化Serializable接口,所以這裏我們將第一個例子中的Test作出一點改變,那就是實現序列化接口。
public class Test implements Serializable{ private String name; public Test() { } public Test(String name) { this.name = name; } public String getName() { return name; } public void setName(String name) { this.name = name; } public static void main(String[] args) throws Exception { String filePath = "sample.txt"; Test t1 = new Test("張三"); try { FileOutputStream fileOutputStream = new FileOutputStream(filePath); ObjectOutputStream outputStream = new ObjectOutputStream(fileOutputStream); outputStream.writeObject(t1); outputStream.flush(); outputStream.close(); FileInputStream fileInputStream = new FileInputStream(filePath); ObjectInputStream inputStream = new ObjectInputStream(fileInputStream); Test t2 = (Test) inputStream.readObject(); inputStream.close(); System.out.println(t2.getName()); } catch (Exception ee) { ee.printStackTrace(); } } }
5.Object對象的clone()方法
Object對象中存在clone方法,它的作用是創建一個對象的副本。看下面的例子,這裏我們依然使用第一個例子的Test類。
public static void main(String[] args) throws Exception { Test t1 = new Test("張三"); Test t2 = (Test) t1.clone(); System.out.println(t2.getName()); }
6.以上五種方法就是所有的方法了,並不存在第六種方法。如果你覺得還有什麼可以創建對象的方法,請評論區留言!