Java - 创建对象的五种方式

1. new关键字

 我们最常用的new关键字创建实例对象

Student stu = new Student();

2. class.newInstance()

Class.newInstance 方法会调用目标类的无参构造方法来创建实例。

try {
    Student stu = Student.class.newInstance();
} catch (InstantiationException | IllegalAccessException e) {
    e.printStackTrace();
}

3. constructor.newInstance()

constructor.newInstance 可以调用任意构造方法(包括有参构造方法),并且可以通过 setAccessible(true) 调用非 public 的构造方法。

try {
    //1. 无参构造
    Constructor constructor = Student.class.getConstructor();
    Student stu1 = constructor.newInstance();

    //2. 有参构造
    Constructor constructorWithParam = Student.class.getConstructor(String.class, Integer.class, String.class);
    Student stu2 = constructorWithParam.newInstance("wyf", 22, "男");
} catch (NoSuchMethodException | IllegalAccessException | InvocationTargetException | InstantiationException e) {
    e.printStackTrace();
}

4.clone

使用clone, 需要类实现 Cloneable 接口,并覆盖 clone 方法( 因为Object类的clone方法是protected修饰的 )。默认的 clone 是浅拷贝,如果需要深拷贝,需要手动实现或使用序列化。

// 浅拷贝
@Data
@NoArgsConstructor
@AllArgsConstructor
public class Student implements Cloneable{

    private String name;
    private Integer age;
    private String sex;
    public Student clone() throws CloneNotSupportedException{
        return (Student) super.clone();
    }
    public static void main(String[] args) throws CloneNotSupportedException {
        Student student1 = new Student("wyf", 22, "男");
        Student student2 = student1.clone();
        System.out.println(student2);
    }
}
// 深拷贝
@Data
@NoArgsConstructor
@AllArgsConstructor
public class Student implements Cloneable{

    private String name;
    private Integer age;
    private String sex;
    private Address address;
    public Student clone() throws CloneNotSupportedException{
        Student student = (Student) super.clone();
        student.address = (Address) this.address.clone(); // 手动克隆引用类型字段
        return student;
    }
    public static void main(String[] args) throws CloneNotSupportedException {
        Student student1 = new Student("wyf", 22, "男",new Address("Beijing"));
        Student student2 = student1.clone();

    }
}

 

5.反序列化

本例反序列化需要类实现 Serializable 接口

平时读取文件进行反序列化, 一般就是直接使用字节流或者字符流来进行处理

@Data
@NoArgsConstructor
@AllArgsConstructor
public class Student implements Serializable {
    private static final long serialVersionUID = 1L; // 唯一标识符,推荐添加

    private String name;
    private Integer age;
    private transient String sex; //使用 transient 关键字标记不需要序列化的字段。

    public static void main(String[] args) {
        Student student1 = new Student("wyf", 22, "男");
        byte[] bytes = SerializationUtils.serialize(student1);
        Student student2 = (Student) SerializationUtils.deserialize(bytes);
        System.out.println(student2);  // 结果: Student(name=wyf, age=22, sex=null)
    }
}

你可能感兴趣的:(java,开发语言)