1.使用 new 關鍵字(最常用)
通過調用類的構造函數直接實例化對象
Person person = new Person(); // 調用無參構造
Person person = new Person("Alice", 25); // 調用有參構造
2.反射機制(動態創建)
利用Java反射 API 在運行時動態創建對象,常用于框架開發
// 通過 Class 對象創建
Class<?> clazz = Class.forName("com.example.Person");
Person person = (Person) clazz.newInstance();// 通過構造器創建(支持有參構造)
Constructor<Person> constructor = Person.class.getConstructor(String.class, int.class);
Person person = constructor.newInstance("Bob", 30);
3.clone()方法(對象復制)
通過實現 Cloneable接口并重寫 clone() 方法,基于現有對象復制一個新對象
class Person implements Cloneable {@Overridepublic Person clone() {try {return (Person) super.clone(); // 調用 Object.clone()} catch (CloneNotSupportedException e) {throw new AssertionError(); }}
}
// 使用克隆
Person original = new Person("Alice", 25);
Person cloned = original.clone(); // 創建新對象
4.反序列化(持久化恢復)
通過 ObjectInputStream 將序列化后的字節流恢復為對象,繞開構造函數,常用于網絡傳輸或持久化存儲
// 序列化對象到文件
ObjectOutputStream out = new ObjectOutputStream(new FileOutputStream("person.bin"));
out.writeObject(new Person("Alice", 25));
out.close();// 反序列化創建對象
ObjectInputStream in = new ObjectInputStream(new FileInputStream("person.bin"));
Person person = (Person) in.readObject(); // 創建新對象
in.close();
這是我整理的自學筆記,目前還在學習階段,文章中可能有錯誤和不足,歡迎大家斧正!