Java 中创建对象的方式

版权声明:转载请标明出处 https://blog.csdn.net/weixin_36759405/article/details/84147266

1. 使用new关键字创建对象

Student stu = new Student();

2. 使用Class类的newInstance方法(反射机制)

// 调用无参的构造器创建对象
Student stu = (Student) Class.forName("Student类全限定名").newInstance(); 

Student stu = Student.class.newInstance();

3. 使用Constructor类的newInstance方法(反射机制)

class Student {
    private int id;
    
    public Student(Integer id) {
        this.id = id;
    }
}
// 可以调用有参数的和私有的构造函数
Constructor<Student> constructor = Student.class.getConstructor(Integer.class);
       
Student stu = constructor.newInstance(123);

4. 使用Clone方法创建对象

class Student implements Cloneable {

    @Override
    public Object clone() throws CloneNotSupportedException {
        return super.clone();
    }
}

5. 使用(反)序列化机制创建对象

class Student implements Serializable {
   private int id;

   public Student(Integer id) {
       this.id = id;
   }
}
Student stu = new Student(123);

// 写对象
ObjectOutputStream output = new ObjectOutputStream(new FileOutputStream("student.bin"));
output.writeObject(stu);
output.close();

// 读对象
ObjectInputStream input = new ObjectInputStream(new FileInputStream("student.bin"));
Student stu = (Student) input.readObject();
System.out.println(stu);

猜你喜欢

转载自blog.csdn.net/weixin_36759405/article/details/84147266