在java中,我可以使用類對象來動態實例化該類型的類嗎?從類對象實例化類
即我想要這樣的功能。
Object foo(Class type) {
// return new object of type 'type'
}
在java中,我可以使用類對象來動態實例化該類型的類嗎?從類對象實例化類
即我想要這樣的功能。
Object foo(Class type) {
// return new object of type 'type'
}
您可以使用Class.newInstance
:
Object foo(Class type)
throws InstantiationException, IllegalAccessException {
return type.newInstance();
}
...但是,假設有一個無參數的構造函數。一個更強大的路線是通過Class.getConstructor
或Class.getConstructors
,它會帶您使用java.lang.reflect
包中的Reflection物件。
用途:
type.newInstance()
對於使用空costructor,或者使用方法type.getConstructor(..)來獲取相關的構造函數,然後調用它創建一個實例。
是的,它被稱爲反射。您可以使用類newInstance()
方法。
使用newInstance()方法。
你可以閱讀更多關於它在: http://java.sun.com/docs/books/tutorial/reflect/index.html 此文章有很好的信息:http://stackoverflow.com /問題/ 37628 /什麼 - 是 - 反射和爲什麼 - 是 - 它無用 – RonK 2010-06-14 11:27:24