Java创建类的五种方式

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;
}
  • 2
    点赞
  • 24
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值