1.通过new xxx()调用构造方法创建对象
2.通过反射创建对象
3.通过反射,调用construct.newInstance()创建对象
4.通过xxx.clone()克隆的方式创建对象
5.通过序列化、反序列化创建对象
public class TestCreateObject {
//1.通过new xxx()调用构造方法创建对象
private static Student creatNewStudent(){
return new Student(UUID.randomUUID().toString(),"丁强");
}
//2.通过反射创建对象
private static Student createClassStudent(){
try {
Student student = Student.class.newInstance();
//得到一个空的对象
student.setId(UUID.randomUUID().toString());
student.setName("雷超");
return student;
} catch (InstantiationException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
}
return null;
}
//3.通过反射,调用construct.newInstance()创建对象
private static Student createConstructStudent(){
//获取Student类对应的CLASS字节码对象
Class studentClass = Student.class;
//获取Student类中有参构造方法
try {
Constructor constructor = studentClass.getConstructor(String.class,String.class);
return constructor.newInstance(UUID.randomUUID().toString(),"马申");
} catch (NoSuchMethodException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
} catch (InstantiationException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
}
return null;
}
//4.通过xxx.clone()克隆的方式创建对象
private static Student createCloneStudent(){
Student studentOne = new Student(UUID.randomUUID().toString(),"吴雨");
try {
return (Student) studentOne.clone();
} catch (CloneNotSupportedException e) {
e.printStackTrace();
}
return null;
}
//5.通过序列化、反序列化创建对象
private static Student createSerializableStudent(){
Student student = new Student(UUID.randomUUID().toString(),"李四");
//将student对象序列化到student.txt文件中
try {
ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream("G:\student.txt"));
ObjectInputStream ois = new ObjectInputStream(new FileInputStream("G:\student.txt"));
oos.writeObject(student);
//从student.txt文件中反序列化出student对象
return (Student) ois.readObject();
} catch (IOException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
return null;
}
public static void main(String[] args) {
System.out.println("第一种方法"+creatNewStudent());
System.out.println("第二种方法"+createClassStudent());
System.out.println("第三种方法"+createConstructStudent());
System.out.println("第四种方法"+createCloneStudent());
System.out.println("第五种方法"+createSerializableStudent());
}
}



