Java中6種建立物件的方法,除了new你還知道啥?

封面
今天來聊一聊在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.以上五種方法就是所有的方法了,並不存在第六種方法。如果你覺得還有什麼可以建立物件的方法,請評論區留言!