Java中创建对象的几种方式。

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}
  • 12
    点赞
  • 30
    收藏
    觉得还不错? 一键收藏
  • 4
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值