[英]Is constructor the only way to create the object of a class in JAVA?
If a constructor is the only way to create the object of a class then how String name = "Java";如果构造函数是创建 object 的唯一方法 class 那么如何 String name = "Java"; is able to create an object of String class even without using constructor.
即使不使用构造函数,也能够创建字符串 class 的 object。
No. Constructor is not the only way.不,构造函数不是唯一的方法。
There are at least two more ways:至少还有两种方式:
Though in case with your example - neither of these is used.尽管以您的示例为例-这些都没有使用。
In this case Java uses string pool在这种情况下 Java 使用字符串池
There is another way of creating objects via还有另一种创建对象的方法
Class.forName("fully.qualified.class.name.here").newInstance()
Class.forName("fully.qualified.class.name.here").getConstuctor().newInstance()
but they call constructor under the hood.但他们在幕后调用构造函数。
Other ways to create objects are cloning via clone()
method and deserialization.创建对象的其他方法是通过
clone()
方法进行克隆和反序列化。
I suppose in a loop-hole type of way you could use the class object too:我想以一种漏洞的方式,您也可以使用 class object:
// 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();
I mean you still use the constructor so it probably doesn't really count.我的意思是你仍然使用构造函数,所以它可能不算数。 But hey, its there!
但是,嘿,它就在那里!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.