- 利用new关键字(最常见,调用了构造函数);
Student student = new Student();
- 运用反射机制,调用java.lang.Class或java.lang.reflect.Constructor类的newInstance()实例方法(调用了构造函数);
Student student = Student.class.newInstance();
Student student = Student.class.getConstructor().newInstance();
- 调用对象的clone()方法(需实现Cloneable接口);
Student.java:
@Override
protected Object clone() throws CloneNotSupportedException {
return super.clone();
}
Student student2 = (Student) student.clone();
- 运用反序列化方法,调用java.io.Object对象的readObject()方法(需实现Serializable接口)。
ObjectOutputStream out = new ObjectOutputStream(new FileOutputStream("data.obj"));
out.writeObject(student);
out.close();
ObjectInputStream in = new ObjectInputStream (new FileInputStream("data.obj"));
Student student3 = (Student)in.readObject();