Java中创建对象的四种方式。
1、使用new关键字调用构造函数创建对象
Student s1 = new Student("huiye",16,100.00);
System.out.println(s1);
Student{name='huiye', age=16, weight=100.0}
2、利用反射创建对象
2.1、使用Class对象的newInstance() 方法
Class<Student> c = Student.class;
Student s2 = (Student) c.newInstance();
s2.setName("huiye");
s2.setAge(17);
s2.setWeight(100.00);
System.out.println(s2);
Student{name='huiye', age=17, weight=100.0}
2.2、通过反射先获取Constructor对象,再调用Construtor对象的newInstance()方法
Class<Student> c = Student.class;
Constructor<Student> constructor = c.getConstructor();
Student s3 = constructor.newInstance();
s3.setName("huiye");
s3.setAge(18);
s3.setWeight(100.00);
System.out.println(s3);
Student{name='huiye', age=18, weight=100.0}
3、使用 clone() 方法克隆一个对象
此方式需要实现 Cloneable 接口,重写 Object 类的 clone() 方法。
public class Student implements Cloneable , Serializable{
.....
@Override
protected Object clone() throws CloneNotSupportedException {
return super.clone();
}
Student s4 = new Student();
s4.setName("huiye");
s4.setAge(19);
s4.setWeight(100.00);
Object clone = s4.clone();
System.out.println(clone);
Student{name='huiye', age=19, weight=100.0}
4、使用对象流 ObjectInputStream的readObject()方法读取序列化对象
此方式需要实现Serializable接口
public class Student implements Cloneable , Serializable{
File file = new File("D:\\Files\\student.txt\\");
ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream(file));
Student s5 = new Student("huiye",20,100.00);
oos.writeObject(s5);
ObjectInputStream ois = new ObjectInputStream(new FileInputStream(file));
Student s6 = (Student) ois.readObject();
System.out.println(s6);
Student{name='huiye', age=20, weight=100.0}