在 Java 中,有什麼方法可以建立物件?


您可以建立一個物件

使用新關鍵字。

Sample obj = new Sample();
  • 使用 newInstance() 方法和 Class.forName() 方法。
Sample obj2 = (Sample) Class.forName("Sample").newInstance();
  • 透過實現 Cloneable 介面(標記)來使用 clone() 方法。
Sample obj3 = (Sample) obj1.clone();
  • 使用類載入器。
Object obj4 = Sample.class.getClassLoader().loadClass("Sample");
  • 從 lang.reflect 中使用建構函式類。
Class cls = Sample.class;
Constructor obj = cls.getDeclaredConstructors()[0];
Sample obj5 = (Sample) obj.newInstance();

更新時間:2020 年 6 月 16 日

163 次瀏覽

開啟你的 職業生涯

完成課程取得認證

開始學習
廣告
© . All rights reserved.