4.Java创建对象有几种方式?
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();
这是我整理的自学笔记,目前还在学习阶段,文章中可能有错误和不足,欢迎大家斧正!