咱们常说,Java是一种面向对象的语言,于是在Java中几乎全部的操做都离不开对象。而在Java语言中,最多见的建立对象的方法是经过对类构造器的调用,除此以外,其实还有下面几种能够建立对象的方法。java
1)经过反射机制来建立对象;this
class Person{ String name="Jack"; public Person(){ System.out.println("construct"); } public String toString(){return name;} } public class Test{ public static void main(String[] args){ Class classType; try{ classType=Class.forname("Person"); Person p = (Person)classType.newInstance(); System.out.println(p); }cathch(Exception e){ e.printStackTrace(); } } }
程序的运行结果为:spa
constructcode
Jack对象
2)调用对象的clone方法,须要如下几个步骤才能使用clone方法:blog
(1)实现clone的类首先须要继承Cloneable接口实质上是一个标识接口,没有任何的接口方法,这一点和序列化接口Serializable()很相似。继承
(2)在类中重写Object类的clone方法。接口
(3)在clone方法中调用super.clone()。不管clone类的继承结构是什么,super.clone()都会直接或间接的调用Java.long.Object类中的clone()方法。get
实例代码以下:it
class Obj implement Cloneable{ private int aInt=0; public Obj(){ System.out.println("construct"); } public int getAint(){return aInt;} public void changeInt(){this.aInt=1; } public Object clone(){ Object o=null; try{ o=(Obj)super.clone(); }catch(CloneNotSuppertedException e){ e.printStackTrace(); } return 0; } } public class Test{ public static void main(String[] args){ Obj a = new Obj(); Obj b = (Obj)a.clone(); b.changeInt(); System.out.println("a:"+a.getAInt()); System.out.println("b:"+b.getAInt()); } }
程序的运行结果为:
construct
a:0
b:1
从以上的程序运行能够看出,在调用a.clone()方法时,系统建立了新的对象,可是没有调用构造方法。
3)经过反序列化的方式建立对象,实例代码以下:
import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.io.Serializable; public class Person implement Serilalizable{ private String name; public Person(){ this.name="lili"; System.out.println("Construct"); } public Stream toString(){return this.name;} public static void main(String args[]){ Person p = new People(); System.out.println(p); ObjectOutputStream oos=null; ObjectInputStream ois = null; try{ FileOutputStream fos =new FileOutputStream("perpke.out"); oos=new ObjectOutputStream(fos); oos.writeObject(p); oos.close(0); } catch(Exception ex){} People pl; try{ FileInputStream fis = new FileInputStream("perple.out"); ois = new ObjectInputStream(fis); p1=(People)ois.readObject(); System.out.println(p); if(p!=p1) System.out.println("two different objecrt") ois.close(); }catch(Exception ex){} } }
程序的运行结果为:
construct
lili
lili
two fifferent object