创建对象的几种方式

tech2022-08-03  183

public class Student implements Cloneable, Serializable { private int id; public Student() { } public Student(Integer id) { this.id = id; } @Override protected Object clone() throws CloneNotSupportedException { // TODO Auto-generated method stub 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); } }/* Output: 使用new关键字创建对象: Student [id=123] --------------------------- 使用Class类的newInstance方法创建对象: Student [id=0] --------------------------- 使用Constructor类的newInstance方法创建对象: Student [id=123] --------------------------- 使用Clone方法创建对象: Student [id=123] --------------------------- 使用(反)序列化机制创建对象: Student [id=123] *///:~

还有一种方式是利用Unsafe类来创建对象,这种方式也不需要构造方法

/** * @author lihai * @date 2020/9/2-21:04 */ 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); } } /** * Customer [id=0, name=null, email=null, birth=null] * Customer [id=0, name=null, email=null, birth=null] */
最新回复(0)