`

Java创建对象的四种方法

    博客分类:
  • java
阅读更多

 

package test;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.ObjectInputStream;
import java.io.Serializable;

public class Test  implements Serializable,Cloneable {
	private static final long serialVersionUID = 0L;
	
	public Test() {
		System.out.println("调用了构造方法");
	}
	
	public Object clone() {
		Object obj = null;
		try {
			obj = super.clone();
		} catch (CloneNotSupportedException e) {
			e.printStackTrace();
		}
		return obj;
	}

	/**
	 * 创建对象的四种方式
	 * 1.使用new关键字   2.反射机制   3.使用clone方法   4.反序列化 
	 */
	public static void main(String[] args) throws Exception {
		//使用new关键字
		Test t1 = new Test();//调用了构造方法
		
		//反射机制
		Class c = (Class)Class.forName("test.Test");
		Test t2 = (Test)c.newInstance();//调用了构造方法
		
		//使用clone方法
		Test t3 = (Test)t2.clone();

		//反序列化
		byte[] head = { -84, -19, 0, 5, 115, 114, 0 };
		byte[] ass = { 0, 0, 0, 0, 0, 0, 0, 0, 2, 0, 0, 120, 112 };
		String name = Test.class.getName();
		ByteArrayOutputStream baos = new ByteArrayOutputStream();
		baos.write(head);
		baos.write(name.length());
		baos.write(name.getBytes());
		baos.write(ass);
		baos.flush();
		baos.close();
		ObjectInputStream ois = new ObjectInputStream(new ByteArrayInputStream(baos.toByteArray()));
		Test t4 = (Test)ois.readObject();

		System.out.println(t1);
		System.out.println(t2);
		System.out.println(t3);
		System.out.println(t4);
	}

}

/*Output:
调用了构造方法
调用了构造方法
test.Test@ca0b6
test.Test@10b30a7
test.Test@1a758cb
test.Test@1b67f74
*/
 

从输出结果看,4个对象处于不同的内存位置,即4个对象互不相等。

 

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics