java创建对象的方法

public class Student {
    String name;
    int age;

    public Student(String name, int age) {
        this.name = name;
        this.age = age;
    }
}
  1. new 一个对象
 Student student = new Student("张三",18);
  1. 克隆一个对象
    需要副本类先实现Clonable接口,并实现其clone()方法
public class Student implements Cloneable{
    String name;
    int age;

    public Student(String name, int age) {
        this.name = name;
        this.age = age;
    }
    @Override
    protected Object clone() throws CloneNotSupportedException {
        return super.clone();
    }
}
 Student student = new Student("张三",18);
        try {
            Student student1 = (Student) student.clone();
        } catch (CloneNotSupportedException e) {
            e.printStackTrace();
        }

快速创建一个和原对象值相同,但是对象引用地址不同的对象。

  1. 反射:派发一个类
 Student student2 = Student.class.newInstance();
  1. 反射:动态加载
Student student3 = (Student) Class.forName("类的全路径").newInstance();
  1. 反射:构造一个对象
  Student student4 = Student.class.getConstructor().newInstance();
  1. 反序列话一个对象
    副本类需要先实现序列化接口
public class Student implements Cloneable, Serializable {
    String name;
    int age;

    public Student(String name, int age) {
        this.name = name;
        this.age = age;
    }
    @Override
    protected Object clone() throws CloneNotSupportedException {
        return super.clone();
    }
}
        // 序列化一个对象
        ObjectOutputStream objectOutputStream = new ObjectOutputStream(new FileOutputStream("student.obj"));
        objectOutputStream.writeObject(student);
        objectOutputStream.close();

        // 反序列化
        ObjectInputStream objectInputStream = new ObjectInputStream(new FileInputStream("student.obj"));
        Student student5 = (Student) objectInputStream.readObject();
        objectInputStream.close();
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容