咱們老是討論沒有對象就去new一個對象,建立對象的方式在我這裏變成了根深蒂固的new方式建立,可是其實建立對象的方式仍是有不少種的,不僅僅有new方式建立對象,還有使用反射機制建立對象,使用clone方法去建立對象,經過序列化和反序列化的方式去建立對象。這裏就總結一下建立對象的幾種方式,來好好學習一下java建立對象的方式。java
這是咱們最多見的也是最簡單的建立對象的方式,經過這種方式咱們還能夠調用任意的夠贊函數(無參的和有參的)。
好比:Student student = new Student();框架
這個newInstance方法調用無參的構造器建立對象,
如:Student student2 = (Student)Class.forName("根路徑.Student").newInstance();
或者:Student stu = Student.class.newInstance();函數
本方法和Class類的newInstance方法很像,java.lang.relect.Constructor類裏也有一個newInstance方法能夠建立對象。我
們能夠經過這個newInstance方法調用有參數的和私有的構造函數。
如: Constructor<Student> constructor = Student.class.getInstance(); Student stu = constructor.newInstance();
這兩種newInstance的方法就是你們所說的反射,事實上Class的newInstance方法內部調用Constructor的newInstance方法。
這也是衆多框架Spring、Hibernate、Struts等使用後者的緣由。學習
論什麼時候咱們調用一個對象的clone方法,JVM就會建立一個新的對象,將前面的對象的內容所有拷貝進去,用clone方法建立對象並不會調用任何構造函數。要使用clone方法,咱們必須先實現Cloneable接口並實現其定義的clone方法。
如:Student stu2 = <Student>stu.clone();
這也是原型模式的應用。spa
當咱們序列化和反序列化一個對象,JVM會給咱們建立一個單獨的對象,在反序列化時,JVM建立對象並不會調用任何構造函數。爲了反序列化一個對象,咱們須要讓咱們的類實現Serializable接口。
如:ObjectInputStream in = new ObjectInputStream (new FileInputStream("data.obj")); 對象
Student stu3 = (Student)in.readObject();接口