【问题标题】:Is constructor the only way to create the object of a class in JAVA?构造函数是在 JAVA 中创建类对象的唯一方法吗?
【发布时间】:2020-08-08 11:49:24
【问题描述】:

如果构造函数是创建类对象的唯一方法,那么如何 字符串名称 = "Java"; 即使不使用构造函数也能够创建 String 类的对象。

【问题讨论】:

标签: java object constructor


【解决方案1】:

我想你也可以以一种漏洞的方式使用类对象:

// Get the class object using an object you already have   
Class<?> clazz = object.getClass();

// or get class object using the type
Class<?> clazz = Object.class;

// Get the constructor object (give arguments 
// of Class objects of types if the constructor takes arguments)
Constructor<?> constructor = clazz.getConstructor();

// then invoke it (and pass arguments if need be)
Object o = constructor.newInstance();

我的意思是你仍然使用构造函数,所以它可能不算数。但是,嘿,它就在那里!

Java doc link for Class object

【讨论】:

    【解决方案2】:

    还有另一种创建对象的方法

    • Class.forName("fully.qualified.class.name.here").newInstance()

    • Class.forName("fully.qualified.class.name.here").getConstuctor().newInstance()

    但他们在后台调用构造函数。

    Other ways 创建对象是通过clone() 方法克隆和反序列化。

    【讨论】:

      【解决方案3】:

      没有。构造函数不是唯一的方法。

      至少还有两种方式:

      1. Clone the object
      2. Serialize and then deserialize 对象。

      尽管以您的示例为例-这些都没有使用。

      在这种情况下,Java 使用string pool

      【讨论】:

        【解决方案4】:

        是的,每次创建新对象时,都会调用至少一个构造函数。

        看看这个tutorial,它会用对象、类和构造函数解释一切。

        【讨论】:

        • 这仅适用于“常规”方式。克隆和反序列化实际上都没有经过构造函数。他们使用 Java 的黑魔法绕过所有这些机制,而是使用直接内置于语言中的机制。
        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2013-03-13
        • 2018-10-31
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多