创建对象的5种方式:
- 最常用的通过new关键字,Object obj = new Object();
- 通过Class类的newInstance()方法,Student.class.newInstance()(已经不推荐使用了);
- 通过Constructor类的newInstance()方法,obj.class.getDeclaredConstructor()方法。调用构造器的方式有三种,new关键字,反射和反序列化,这里采用的是第二种方式。
- Clone()方法,分为深复制和浅复制,深复制复制对象及引用的对象,浅复制只复制引用,不复制引用的对象。
- 序列化,序列化就是将对象的状态转换为字节流,反序列化是将字节流生成相同状态的对象。序列化的作用:(1).网络上传输(2)实现数据的持久化
这篇文章主要讲一下clone()方法的使用,下一篇再谈序列化。
clone()方法
clone()方法分为深复制和浅复制,区别在于复制引用还是复制引用的对象。此外,clone()是个native方法,前面的文章已经提到,并与相关方法做了比较。
(1), 浅复制
class Student implement Cloneable{
public Integer id;
public String name;
public Grade grade;
public Student(Integer id,String name,Grade grade){
this.id = id;
this.name = name;
this.grade = grade;
}
@Override
protected Student clone() throws CloneNotSupportedException {
return (Student)super.clone();
}
}
class Grade implement Cloneable{
public String name;
public Integer score;
public Grade(String name,Integer score){
this.name = name;
this.score = score;
}
@Override
protected Student clone() throws CloneNotSupportedException {
return (Student)super.clone();
}
}
(2)深复制
class Student implement Cloneable{ public Integer id; public String name; public Grade grade; public Student(Integer id,String name,Grade grade){ this.id = id; this.name = name; this.grade = grade; } @Override protected Student clone() throws CloneNotSupportedException {
Student student = (Student)super.clone();
student.grade = (Grade)grade.clone();
return student; } }
使用clone方法的步骤:
1)被克隆的类要实现Cloneable接口。
2)被克隆的类要重写clone()方法。
cloneable接口中没有任何的方法,它的作用只是用来只是可以使用Object的clone()方法进行合法的克隆,如果不实现接口直接调用就会CloneNotSupportedException。
效率分析:
clone()创建对象的方法要比new一个对象要快很多,因为clone是本地方法,直接对内存中的二进制流进行操作,特别是在创建一个大对象时,性能差别很大的。