一、创建对象的四种方式
首先准备一个Student实体类进行测试。
import java.io.Serializable;
/**
* @author zll
* @version 1.0
* @date 2020/6/9 16:54
*/
public class Student implements Serializable, Cloneable {
private String name;
private Integer age;
private String sex;
@Override
protected Object clone() throws CloneNotSupportedException {
return super.clone();
}
public Student() {
}
@Override
public String toString() {
return this.getClass()+"Student{" +
"name='" + name + '\'' +
", age=" + age +
", sex='" + sex + '\'' +
'}';
}
public Student(String name, Integer age, String sex) {
this.name = name;
this.age = age;
this.sex = sex;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
public String getSex() {
return sex;
}
public void setSex(String sex) {
this.sex = sex;
}
}
1、new关键字
/**
* 1、通过关键字:new,创建一个对象
* @author zll
* @version 1.0
* @date 2020/6/9 16:57
*/
public class Test01 {
public static void main(String[] args){
Student stu1=new Student("Lily",18,"girl");
Student stu2=new Student("Tom",19,"boy");
System.out.println(stu1.toString());
System.out.println(stu2.toString());
}
}
2、反射
/**
* 2、通过反射创建对象
* @author zll
* @version 1.0
* @date 2020/6/9 17:00
*/
public class test02 {
public static void main(String[] args) throws Exception{
//new一个对象
Student instance = new Student();
//通过反射创建一个对象
Class c = Student.class;
Constructor constructor = c.getDeclaredConstructor();
constructor.setAccessible(true);
Student newInstance = (Student) constructor.newInstance();
System.out.println(instance);
System.out.println(newInstance);
}
}
3、序列化
实体类需要实现Serializable接口。
/**
* 3、序列化创建对象
* 一个对象实现了Serializable接口,就可以把对象写入到文件中,并通过读取文件来创建对象。
* @author zll
* @version 1.0
* @date 2020/6/9 17:19
*/
public class test03 {
public static void main(String [] args) throws Exception{
Student instance =Student.class.newInstance();
ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream("file"));
oos.writeObject(instance);
File f = new File("file");
ObjectInputStream ois = new ObjectInputStream(new FileInputStream(f));
Student newInstance2 = (Student) ois.readObject();
System.out.println(newInstance2.toString());
}
}
4、clone
实体类需要实现Cloneable接口,重写run方法。
/**
* 4、clone创建对象
* @author zll
* @version 1.0
* @date 2020/6/9 17:28
*/
public class test04 {
public static void main(String[] args) throws Exception {
Student stu1=new Student("赵四",34,"男");
Student stu2=(Student) stu1.clone();
stu2.setAge(80);
System.out.println(stu1.toString());
System.out.println(stu2.toString());
}
}