Java 中创建对象的方式

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);
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值