java面试题-创建对象的五种方式

/**
 * java 创建对象五种方式
 *
 */
public class BuildObject implements Cloneable,Serializable{

	public static void main(String[] args) throws ClassNotFoundException, InstantiationException, IllegalAccessException, NoSuchMethodException, SecurityException, IllegalArgumentException, InvocationTargetException, CloneNotSupportedException, FileNotFoundException, IOException {
		//1.通过new
		BuildObject objNew=new BuildObject();
		objNew.build("objNew");
		//2.通过Class类的newInstance
		BuildObject objClass= (BuildObject) Class.forName("com.ecit.lyy.buildObj.BuildObject").newInstance();
		objClass.build("objClass");
		//3.通过Constructor类的newInstance方法
		Constructor constructor=BuildObject.class.getConstructor();
		BuildObject objCons=constructor.newInstance();
		objCons.build("objCons");
		//4.使用clone方法:需要实现Cloneable接口
		BuildObject objClone=(BuildObject)objNew.clone();
		objClone.build("objClone");
		//5.使用反序列化
		ObjectOutputStream out=new ObjectOutputStream(new FileOutputStream("data.obj"));
		out.writeObject(objNew);
		out.close();
		ObjectInputStream in=new ObjectInputStream(new FileInputStream("data.obj"));
		BuildObject objSeri=(BuildObject) in.readObject();
		in.close();
		objSeri.build("objSeri");
	}
	
	void build(String fun){
		System.out.println("hashCode :"+this.hashCode());
		System.out.println(fun+" : build object success!!!");
	}
	
	
}

 

 

结果输出:

hashCode :366712642
objNew : build object success!!!
hashCode :1829164700
objClass : build object success!!!
hashCode :2018699554
objCons : build object success!!!
hashCode :1311053135
objClone : build object success!!!
hashCode :990368553
objSeri : build object success!!!

 

你可能感兴趣的:(JAVA)