public class Student implements Cloneable, Serializable
{
private int id
;
public Student() {
}
public Student(Integer id
) {
this.id
= id
;
}
@Override
protected Object
clone() throws CloneNotSupportedException
{
return super.clone();
}
@Override
public String
toString() {
return "Student [id=" + id
+ "]";
}
public static void main(String
[] args
) throws Exception
{
System
.out
.println("使用new关键字创建对象:");
Student stu1
= new Student(123);
System
.out
.println(stu1
);
System
.out
.println("\n---------------------------\n");
System
.out
.println("使用Class类的newInstance方法创建对象:");
Student stu2
= Student
.class.newInstance();
System
.out
.println(stu2
);
System
.out
.println("\n---------------------------\n");
System
.out
.println("使用Constructor类的newInstance方法创建对象:");
Constructor
<Student> constructor
= Student
.class
.getConstructor(Integer
.class);
Student stu3
= constructor
.newInstance(123);
System
.out
.println(stu3
);
System
.out
.println("\n---------------------------\n");
System
.out
.println("使用Clone方法创建对象:");
Student stu4
= (Student
) stu3
.clone();
System
.out
.println(stu4
);
System
.out
.println("\n---------------------------\n");
System
.out
.println("使用(反)序列化机制创建对象:");
ObjectOutputStream output
= new ObjectOutputStream(
new FileOutputStream("student.bin"));
output
.writeObject(stu4
);
output
.close();
ObjectInputStream input
= new ObjectInputStream(new FileInputStream(
"student.bin"));
Student stu5
= (Student
) input
.readObject();
System
.out
.println(stu5
);
}
}
还有一种方式是利用Unsafe类来创建对象,这种方式也不需要构造方法
public class Test {
@org.junit
.Test
public void tt() throws Exception
{
Customer customer
= new Customer();
System
.out
.println(customer
);
Field field
= Unsafe
.class.getDeclaredField("theUnsafe");
field
.setAccessible(true);
Unsafe unsafe
= (Unsafe
) field
.get(null
);
Customer customer1
= (Customer
) unsafe
.allocateInstance(Customer
.class);
System
.out
.println(customer1
);
}
}