Java语言创建对象的几种方法。
一,使用new关键字创建。
二,使用class类的 newInstance的方法创建。反射机制。
Student student = (Student)Class.forName("根路径.Student").newInstance();
或者,Student stu = Student.class.newInstance();
三,使用Constructor类的newInstance方法:本方法和class类的newInstance方法很像。也可以创建对象。
Constructor<Student> constructor = Student.class.getInstance();
Student stu = constructot.newInstance();
四,使用clone的方法,
无论何时我们调用一个对象的clone方法,JVM就会创建一个新的对象,将前面的对象的所有的内容全部拷贝进去,用clone的方法创建对象并不会调用任何构造函数。要使用clone的方法,必须先实现Cloneable接口,并实现其定义的clone方法。
Student stu2 =<Student>stu.clone(); 这也是原型模式的应用。
5.使用反序列化:
当我们序列化和反序列化的时候,JVM就会创建一个对象,在反序列化的时候,JVM创建对象并不会调用任何构造函数。为了反序列化一个对象,我们需要让我们类实现Serializable接口。
ObjectInputStream in = new ObjectInputStream(new FileInputStream("data.obj"));
Student stu3 =(Student)in.readObject();
注意newInstance的区别:
CLASS类位于java的lang中;而构造器类是反射机制的一部分;
class类的newInstance只能触发无参数的构造方法创建对象,而构造器类的newInstance能触发有参数或者任意参数的构造方法来创建对象。
class类的newInstance需要其构造方法是共有的或者再对调用方法可见的,而构造器类的newInstance可以在特定环境下调用私有的构造方法来创建对象。
class类的newInstance抛出类的构造函数异常,而构造器类的newInstance包装了一个invocationTargetException异常。
class类本质上调用了反射包构造器类中无参数的newInstance方法,捕获了invocationTargetException,将构造器的本身异常抛出。