java 创建对象的几种方式

1.用new语句创建对象

2.运用反射手段

3.调用对象的clone()方法

4.运用反序列化手段

代码

//new
        Student student = new Student();
        student.setAge("12");
        student.setClassName("三年级一班");
        System.out.println(student);

        //反射-Contructor
        Constructor constructor = Student.class.getConstructor();
        Student student1  = constructor.newInstance();
        System.out.println(student1);

        //反射-newInstance
        Student student2  = Student.class.newInstance();
        System.out.println(student2);

        //clone
        Student student3 = student.clone();
        System.out.println(student3);

        //反序列化
        FileInputStream fileInputStream = new FileInputStream("E://tmp/employee.ser");
        ObjectInputStream objectInputStream = new ObjectInputStream(fileInputStream);
        Student student4 = (Student) objectInputStream.readObject();
        System.out.println(student4);

java 创建对象的几种方式

Original: https://www.cnblogs.com/excellencesy/p/14382001.html
Author: song.yan
Title: java 创建对象的几种方式

原创文章受到原创版权保护。转载请注明出处:https://www.johngo689.com/537449/

转载文章受原作者版权保护。转载请注明原作者出处!

(0)

大家都在看

亲爱的 Coder【最近整理,可免费获取】👉 最新必读书单  | 👏 面试题下载  | 🌎 免费的AI知识星球