zoukankan      html  css  js  c++  java
  • Java 创建对象的几种方式

    Java 创建对象的几种方式

    • 使用new关键字

      Student student = new Student();
      
    • Class 类的 newInstance() 方法

      ​ 我们也可以使用 Class 类的 newInstance() 方法创建对象,如:

      Student student2 = (Student)Class.forName(className全类名).newInstance();
      // 或者:
      Student stu = Student.class.newInstance();
      
    • Constructor 类的 newInstance() 方法
      该方式和 Class 类的 newInstance() 方法很像。java.lang.relect.Constructor 类里也有一个newInstance方法可以创建对象。我们可以通过这个 newInstance() 方法调用有参数的和私有的构造函数。

      Constructor 类 -- > 声明构造函数的类

      Constructor<Student> constructor = Student.class.getConstructor();
      Student stu = constructor.newInstance();
      
    • Clone()
      无论何时我们调用一个对象的 clone() 方法,JVM 都会创建一个新的对象,同时将前面的对象的内容全部拷贝进去。事实上,用 clone() 方法创建对象并不会调用任何构造函数。需要注意的是,要使用 clone 方法,我们必须先实现 Cloneable 接口并实现其定义的 clone() 方法。

      Student stu2 = <Student>stu.clone();
      
    • 反序列化
      Java 中常常进行 JSON 数据跟 Java 对象之间的转换,即序列化和反序列化。
      当我们序列化和反序列化一个对象,JVM 会给我们创建一个单独的对象,在反序列化时,JVM 创建对象并不会调用任何构造函数。为了反序列化一个对象,我们需要让我们的类实现 Serializable 接口,虽然该接口没有任何方法。

      ObjectInputStream in = new ObjectInputStream (new FileInputStream("data.obj")); 
      Student stu3 = (Student)in.readObject();
      
  • 相关阅读:
    monitor system
    monitor disk
    manage account
    windows
    backup daily
    shell 脚本编程概述
    OGNL表达式
    Struts2各个功能详解(2)-输入校验和拦截器
    struts2各个功能详解(1)----参数自动封装和类型自动转换
    Struts2源码解析2
  • 原文地址:https://www.cnblogs.com/hellojava404/p/13174537.html
Copyright © 2011-2022 走看看