java创建对象的几种方式
https://blog.csdn.net/m0_47683853/article/details/109017364
new、反射、反序列化、clone
1.
new object(xxx);
2.
Class clazz = Dog.class; Dog dog = (Dog)clazz.newInstance();
Class clazz=Dog.class;
Constructor constructor=clazz.getConstructor(String.class,int.class});
Dog dog=(Dog) constructor.newInstance(“xiaohei”,3});
System.out.println(dog.name+” “+dog.age);
3.
Dog dog=new Dog();
dog.name=”xiaohei”;
dog.age=3;
FileOutputStream fos = new FileOutputStream(“dog.txt”);
ObjectOutputStream ops = new ObjectOutputStream(fos);
ops.writeObject(dog);
System.out.println(“dog对象序列化完成”);
FileOutputStream fos=new FileOutputStream(“dog.txt”);
ObjectInputStream ois=new ObjectInputStream(fos);
Dog dog=(Dog) ois.readObject();
System.out.println(“我叫”+dog.name+”今年”+dog.age+”岁了”);
System.out.println(“对象反序列化完成”);
4.
我们现在就来完成clone的实验,首先我们需要在需要clone的类中实现Cloneable接口,否则会出现java.lang.CloneNotSupportedException异常,由于Object类中clone方法是protected 修饰的,所以我们必须在需要克隆的类中重写克隆方法
public class Dog implements Cloneable{
String name;
int age;
@Override
protected Object clone() throws CloneNotSupportedException {
//TODO Auto-generated method stub
return super.clone();
}
}
现在进入实验1:
Dog d1=new Dog();
Dog d2=d1;
System.out.println(d1==d2);
Dog d1=new Dog(); Dog d2=(Dog) d1.clone(); System.out.println(d1==d2);
实验结果为false,因为clone是真实在内存中重新划分一块区域来存储新的对象,d1和d2是两个不同的对象所以返回结果值为false
这样我们就使用了对象的克隆的方式完成了java对象的创建