[英]Is constructor the only way to create the object of a class in JAVA?
如果構造函數是創建 object 的唯一方法 class 那么如何 String name = "Java"; 即使不使用構造函數,也能夠創建字符串 class 的 object。
還有另一種創建對象的方法
Class.forName("fully.qualified.class.name.here").newInstance()
Class.forName("fully.qualified.class.name.here").getConstuctor().newInstance()
但他們在幕后調用構造函數。
創建對象的其他方法是通過clone()
方法進行克隆和反序列化。
我想以一種漏洞的方式,您也可以使用 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();
我的意思是你仍然使用構造函數,所以它可能不算數。 但是,嘿,它就在那里!
是的,每次創建一個新的 object 時,都會調用至少一個構造函數。
看看這個教程,這將解釋所有的對象、類和構造函數。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.