我們可以透過哪些方式建立 Java 中的物件?


你可以建立一個物件

使用 new 關鍵字。

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.