java创建对象的方法

2022-06-27  本文已影响0人  糯米团子123
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();
上一篇 下一篇

猜你喜欢

热点阅读