Java中创建的几种方式。记录一下

  • new关键字创建
  • 通过Class类的newInstance()
  • 通过构造器的newInstance()
  • 通过clone()创建
  • 通过序列化创建

new关键字创建

Student student = new Student();

通过Class类的newInstance()

class Student {
    public Integer age = 1;

}
Class<Student> clazz = Student.class;
    try {
        Student student = clazz.newInstance();
        System.out.println(student.age);
    } catch (InstantiationException | IllegalAccessException e) {
        throw new RuntimeException(e);
    }

通过构造器的newInstance()

Class<Student> clazz = Student.class;
  try {
      Constructor<Student> constructor = clazz.getConstructor();
      Student student = constructor.newInstance();
      System.out.println(student.age);
  } catch (InstantiationException | IllegalAccessException | InvocationTargetException |
           NoSuchMethodException e) {
      throw new RuntimeException(e);
  }

如果通过此方式创建类,要在类中显示的申明无参构造函数。
如果进行有参构造,则在getConstructor()函数中传递有参构造中需要的参数类。同时在newInstance()中传递参数。
getConstructor()函数:
在这里插入图片描述newInstance()函数:
在这里插入图片描述

使用clone()的手段

该方法需要在被克隆类中重新clone()方法,并且实现Cloneable接口,否则将会报错(CloneNotSupportedException)

@Override
    public Student clone() {
        try {
            return (Student) super.clone();
        } catch (CloneNotSupportedException e) {
            throw new AssertionError();
        }
    }
Student student = new Student();
Student clone = student.clone();
System.out.println(clone);

使用序列化手段

注意:类应该先实现接口(Serializable )

public class Example {
    public static void main(String[] args) throws IOException, ClassNotFoundException {
        Path path = Paths.get("obj");
        // 序列化
        ObjectOutputStream outputStream = new ObjectOutputStream(Files.newOutputStream(path));
        Student empObj = new Student();
        outputStream.writeObject(empObj);
        outputStream.close();

        // 反序列
        ObjectInputStream in = new ObjectInputStream(Files.newInputStream(path));
        Student o = (Student) in.readObject();
        System.out.println(o);
    }
}


class Student implements Serializable {
    private static final long serialVersionUID = -3579256460164972451L;
    public Integer age = 1;
    public String name;
}
Logo

旨在为数千万中国开发者提供一个无缝且高效的云端环境,以支持学习、使用和贡献开源项目。

更多推荐