文章目录
Java中到底有多少种方法可以创建一个对象呢?
用再熟悉不过的Student类开干:
public class Student {
private int age;
private String name;
public Student() {
}
public Student(int age, String name) {
this.age = age;
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
1、使用new关键字,调用任意的构造函数就可以实现。
public static void main(String[] args) {
Student stu1 = new Student();
Student stu2 = new Student(18, "小红");
}
2、通过反射,使用Class类的newInstance方法,调用了无参构造函数。
public static void main(String[] args) throws InstantiationException,
IllegalAccessException, ClassNotFoundException {
Student stu1 = Student.class.newInstance();
Student stu2 = (Student) Class.forName("test.Student").newInstance();
}
这里注意,如果没有无参构造函数,上面就会报错的。
3、通过反射,使用Constructor类的newInstance方法,可以调用任何构造方法。
public static void main(String[] args) throws NoSuchMethodException,
SecurityException, InstantiationException, IllegalAccessException,
IllegalArgumentException, InvocationTargetException {
Student stu1 = Student.class.getConstructor().newInstance();
Student stu2 = Student.class.getConstructor().newInstance(18, "小红");
}
4、使用clone方法,没有调用构造函数。
要使用clone方法,要先实现Cloneable接口并重写Object中的clone方法。 在不实现Cloneable接口的实例上调用对象的克隆方法导致抛出异常CloneNotSupportedException,注意,此接口不包含clone方法。 因此,只能通过实现该接口的实例来克隆对象是不可能的,还要重写clone方法。
public class Student implements Cloneable {
private int age;
private String name;
public Student() {
}
public Student(int age, String name) {
this.age = age;
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
@Override
protected Object clone() throws CloneNotSupportedException {
Student stu = null;
try {
stu = (Student) super.clone();
} catch (Exception e) {
e.printStackTrace();
}
return stu;
}
@Override
public String toString() {
return "[name=" + name + ", age=" + age + "]";
}
}
public static void main(String[] args) throws CloneNotSupportedException {
Student stu1 = new Student(18, "是小红鸭");
Student stu2 = (Student) stu1.clone();
System.out.println(stu1.toString());
System.out.println(stu2.toString());
}
5、使用反序列化,将原来序列化到文件中的对象信息反序列化,没有调用构造函数。
不知道序列化与反序列化的看这里:https://blog.csdn.net/qq_42570601/article/details/103396656