首页  

java中创建对象的五种方式     所属分类 java 浏览量 1074
使用new
使用反射 Class newInstance
使用反射 Constructor newInstance
使用clone方法	  (不会调用构造函数)
使用反序列化	 (不会调用构造函数)
使用unsafe  (不会调用构造函数)


一个例子讲清楚

反射 序列化 反序列化  clone 
Cloneable 接口 
Serializable 接口
浅拷贝 与 深拷贝

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.lang.reflect.Constructor;

public class ObjectCreateTest {
	
	public static void main(String[] args) throws Exception {
		// new 创建对象 
		Man man = new Man();
		System.out.println("man="+man);
		
		// 使用反射 Class newInstance
		man = (Man)Class.forName("dyyx.obj.Man").newInstance();
		System.out.println("man="+man);
	
		//  使用反射 Constructor newInstance
		Constructor< Man> constructor = Man.class.getConstructor(new Class[]{});
        // man = constructor.newInstance(new Object[]{});
        man = constructor.newInstance();
		System.out.println("man="+man);
		man.department = new Department();
		System.out.println("man.department="+man.department);

		
        // 使用clone方法	  (不会调用构造函数)
		// 浅拷贝 man 和 man1的 department 指向同一个对象 
		Man man1 = man.clone();
		System.out.println("man1="+man1);
		System.out.println("man1.department="+man1.department);
		
		//// 使用反序列化	 (不会调用构造函数)
		ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
		ObjectOutputStream objectOutputStream = new ObjectOutputStream(byteArrayOutputStream);
		objectOutputStream.writeObject(man1);
		System.out.println("byteArrayOutputStream.size()="+byteArrayOutputStream.size());

		ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(byteArrayOutputStream.toByteArray());
		
		ObjectInputStream objectInputStream = new ObjectInputStream(byteArrayInputStream);
        Man man2 = (Man) objectInputStream.readObject();
        System.out.println("man2="+man1);
		System.out.println("man2.department="+man2.department);
		
		//// 深拷贝
		
		ManDeepCopy man5 = new ManDeepCopy();
		System.out.println("man5="+man5);
		man5.department = new Department();
		System.out.println("man5.department="+man5.department);
		
		// 深拷贝 department 指向不同的对象
		ManDeepCopy man6 = man5.clone();
		System.out.println("man6="+man6);
		System.out.println("man6.department="+man6.department);
	}
}

Pet pet2 = (Pet) unsafe.allocateInstance(Pet.class);
// 0 , 只给对象分配内存 , 不会初始化
System.out.println("unsafe.allocateInstance age2="+pet2.getAge());

完整代码
https://gitee.com/dyyx/hellocode/blob/master/src/dyyx/obj/ObjectCreateTest.java

 unsafe要点 

上一篇     下一篇
linux进程分析方法汇总

linux资源监控atop

linux运维知识点

java有意思的陷阱

synchronized知识点

TCP 重传 滑动窗口 流量控制 拥塞控制