构建Java对象的五种方法

版权声明:请附链接,自由转载 https://blog.csdn.net/kangkanglou/article/details/82020570
  • 使用new关键字

    Employee emp1 = new Employee();

  • 使用Class.newInstance方法

    Employee emp2 = (Employee) Class.forName(“*.Employee”)
    .newInstance();

    OR

    Employee emp2 = Employee.class.newInstance();

  • 使用Constructor类的newInstance()

    Constructor constructor = Employee.class.getConstructor();
    Employee emp3 = constructor.newInstance();

本质上,两种newInstance方法都是反射,而事实上Class.newInstance方法内部调用的也是Constructor类的newInstance的方法,推荐使用Constructor类的newInstance的方法,像Spring、Hibernate、Struts等框架也就是使用的Constructor类的newInstance的方法

  • clone()方法

    Employee emp4 = (Employee) emp3.clone();

  • 使用deserialization反序列化

    ObjectInputStream in = new ObjectInputStream(new FileInputStream(“data.obj”));
    Employee emp5 = (Employee) in.readObject();

https://programmingmitra.blogspot.com/2016/05/different-ways-to-create-objects-in-java-with-example.html

猜你喜欢

转载自blog.csdn.net/kangkanglou/article/details/82020570