public class Student {
String name;
int age;
public Student(String name, int age) {
this.name = name;
this.age = age;
}
}
- new 一个对象
Student student = new Student("张三",18);
- 克隆一个对象
需要副本类先实现Clonable接口,并实现其clone()方法
public class Student implements Cloneable{
String name;
int age;
public Student(String name, int age) {
this.name = name;
this.age = age;
}
@Override
protected Object clone() throws CloneNotSupportedException {
return super.clone();
}
}
Student student = new Student("张三",18);
try {
Student student1 = (Student) student.clone();
} catch (CloneNotSupportedException e) {
e.printStackTrace();
}
快速创建一个和原对象值相同,但是对象引用地址不同的对象。
- 反射:派发一个类
Student student2 = Student.class.newInstance();
- 反射:动态加载
Student student3 = (Student) Class.forName("类的全路径").newInstance();
- 反射:构造一个对象
Student student4 = Student.class.getConstructor().newInstance();
- 反序列话一个对象
副本类需要先实现序列化接口
public class Student implements Cloneable, Serializable {
String name;
int age;
public Student(String name, int age) {
this.name = name;
this.age = age;
}
@Override
protected Object clone() throws CloneNotSupportedException {
return super.clone();
}
}
// 序列化一个对象
ObjectOutputStream objectOutputStream = new ObjectOutputStream(new FileOutputStream("student.obj"));
objectOutputStream.writeObject(student);
objectOutputStream.close();
// 反序列化
ObjectInputStream objectInputStream = new ObjectInputStream(new FileInputStream("student.obj"));
Student student5 = (Student) objectInputStream.readObject();
objectInputStream.close();
网友评论