Java 创建对象的四种方式

42 阅读1分钟

Java 创建对象的四种方式

java中提供了一下四种创建对象的方式:

new创建新对象

Student student = new Student();

通过反射机制

默认构造器方法:

Student student = Student.class.newInstance();

构造器创建:

//默认空参构造器构造
Student student = Student.class.getConstructor().newInstance();
//指定构造器构造
Student student1=Student.class.getConstructor(int.class).newInstance(1);
​

采用clone机制

注意是使用深拷贝方式对已有对象进行克隆,从而创建新的对象

Student student = new Student();
Student clone = student.clone();

原本类要实现Cloneable 接口,并且重写clone 方法,实现深拷贝

通过序列化机制

其实就是将创建好的对象通过序列化写在流里持久化在本地,然后根据需要将流读取出来重新构造一个相同的对象

Student student = (Student) new ObjectInputStream(new
                             FileInputStream("file.txt")).readObject();
​