Java类初始化和实例化

Java有以下几种方式创建类对象:

  • 利用new关键字
  • 利用反射Class.newInstance
  • 利用Constructor.newIntance(相比Class.newInstance多了有参和私有构造函数)
  • 利用Cloneable/Object.clone()
  • 利用反序列化

Constructor.newInstance不支持带原型入参的构造函数。

调用Class.getConstructor()方法获取无参默认构造Constructor时,如果用户自定义了有参构造函数,因为此时java并不会生成默认构造函数,所以Class.getConstructor()方法因找不到无参默认构造函数而抛异常。此时需要显示定义默认构造函数:

// Initialization.java
public class Initialization {
    private int age = 2000;
    private int salary = age + 1000;
    private String name = "Tom";

    public Initialization() {
        print();
    }

    public Initialization(Integer salary, String name) {
        print();

        this.salary = salary;
        this.name = name;

        print();
    }

    /**
    * Static code
    */
    {
        salary += 500;
    }

    private void print() {
        System.out.println("age=" + this.age);
        System.out.println("salary=" + this.salary);
        System.out.println("name=" + this.name);
    }

    public static Initialization construct(int salary, String name) throws Exception {
        Constructor<Initialization> constructorWithNoParams = Initialization.class.getConstructor();
        Constructor<Initialization> constructorWithParams = Initialization.class.getConstructor(Integer.class, String.class);
        return salary <= 0 || name == null ? constructorWithNoParams.newInstance() : constructorWithParams.newInstance(salary, name);
    }

    public Initialization deSerialize() throws Exception {
        // 写对象
        ObjectOutputStream output = new ObjectOutputStream(new FileOutputStream("student.txt"));
        output.writeObject(this);
        output.close();

        // 读取对象
        ObjectInputStream input = new ObjectInputStream(new FileInputStream("student.txt"));
        return (Initialization) input.readObject();
    }
}

再来看下Initialization类被编译为.class文件后的信息:

原文链接

猜你喜欢

转载自blog.csdn.net/weixin_40581617/article/details/83413939