- 通过 new 关键字来创建对象,这个是我们开发中手动创建对象最常用的方式,可以为类增加不同的构造器,然后通过 new 关键字根据不同的构造器参数自动选择正确的构造器来产生一个对象。
- 通过 Class 的 newInstance() 方法创建,该方法会调用类的无参构造器,如果仅提供了有参构造器,则会报 NoSuchMethodException 错误而无法创建。
- 通过 Constructor 的 newInstance() 方法,该方式可以调用有参构造器,如下:
Student stu1 = Student.class.getConstructors()[0].newInstance(); Student stu2 = Student.class.getConstructors()[1].newInstance("张三") ... class Student { String name; public Student() { } public Student(String name) { this.name = name; } }
-
通过实现 Cloneable 接口,实现 clone() 方法,如下:
Student stu1 = new Student("zhangsan"); try { Student stu2 = (Student) stu1.clone(); } catch (CloneNotSupportedException e) { e.printStackTrace(); } ... class Student implements Cloneable { String name; public Student() { } public Student(String name) { this.name = name; } @Override protected Object clone() throws CloneNotSupportedException { return super.clone(); } }
-
通过反序列化,如下:
ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream("stu.txt")); ObjectInputStream ois = new ObjectInputStream(new FileInputStream("stu.txt")); Student stu1 = new Student("zhangsan"); oos.writeObject(stu1); try { Student stu2 = (Student) ois.readObject(); } catch (ClassNotFoundException e) { e.printStackTrace(); } ... class Student implements Serializable { String name; public Student() { } public Student(String name) { this.name = name; } }
以上为五种产生对象的方式,其中1和3可调用任意构造器,2调用无参构造器,4和5不调用构造器,各种框架一般采用3的方式来代理产生对象。