2015-04-01 47 views
0

我想使用android系統中反射的按鈕,通過下面的代碼Android:如何使用Reflection創建對象並傳遞構造函數參數?

public String createView(String classFullName){ 
     try{ 
      Class clazz = Class.forName(classFullName); 

      Object obj = clazz.newInstance(); // but I need to pass the Context using this; 


     } 
     catch(ClassNotFoundException ex){ 
      return null; 
     } 
    } 

但主要問題,是如何通過上下文(這在我的情況下)的對象,因爲他們都應該是一個看法。

+2

你需要去,是以環境,然後調用'的newInstance()'的構造函數構造對象的引用。看看這裏:http://tutorials.jenkov.com/java-reflection/constructors.html – 2015-04-01 19:29:31

+0

@Blackbelt沒有這樣的方法。 – 2015-04-01 19:34:17

回答

4

方法Class#newInstance()只是調用零參數構造函數的便捷方法。如果要使用參數調用構造函數,則需要使用Class#getConstructor(Class...)反射來獲取正確的Constructor實例,然後使用Constructor#newInstance(Object...)調用它。

所以:

Class clazz = Class.forName(classFullName); 
Constructor<?> constructor = clazz.getConstructor(Context.class); 
Object obj = constructor.newInstance(this); 
相關問題