2011-08-18 22 views
0

我在Android中使用Reflection創建一個newInstance調用時遇到問題。Android,界面,新實例

我的接口:

public interface IGiver { 
    public int getNr(); 
} 

我的班級叫反思:

public class NrGiver implements IGiver { 
    int i = 10; 
    @Override 
    public int getNr() { 
     return i; 
    } 
} 

我打電話getNr方式:

String packageName = "de.package"; 
String className = "de.package.NrGiver"; 

String apkName = getPackageManager().getApplicationInfo(packageName, 0).sourceDir; 
      PathClassLoader myClassLoader = 
       new dalvik.system.PathClassLoader(
          apkName, 
         ClassLoader.getSystemClassLoader()); 
Class c = Class.forName(className); 
IGiver giver = (IGiver) c.newInstance(); 

最後一行不會工作就引起錯誤和我的應用程序停止。 我知道它是newInstance的錯,但我想在IGiver對象上工作。

請幫幫我。

我的解決方案:

嘿傢伙們最後我得到了雞。

我找到了其他方法。這次我也使用了newInstance,但這次它的工作。 我的解決方案:

Class c = Class.forName(className); 
Method methode = c.getDeclaredMethod("getNr"); 
Object i = methode.invoke(c.newInstance(), new Object[]{}); 

而這就是我想要做的。 我的手機上有一個NrGiver.class文件。它實現了Interface IGiver。所以它可以動態加載到我的應用程序中。我需要NrGiver類的Integer。所以我可以使我的代碼通用。我試圖將對象投射到我的界面,但失敗了。

所以我找到了另一種方法來調用一個類的方法。

線2的forName THX的幫助

+0

接口不能有任何實例,這就是爲什麼它不會工作 – Egor

+0

出現錯誤?什麼錯誤,確切地說?使用logcat。 – Jems

+0

@Egor我認爲它不是一個接口。它是一個類NrGiver。 IGiver是一個界面。 – Neon

回答

0
String className = "de.package.NrGiver";//line 1 
Class c = Class.forName(className);//line 2 
IGiver giver = (IGiver) c.newInstance();//line3 

正在試圖尋找一個類,但字符串是表示接口,因此類加載器沒有找到類,它拋出一個異常。添加到它,在行3你試圖得到一個不存在於java world ..我的意思是說接口不能instanciated和他們沒有構造函數。

+0

這是如何實例化接口? 'newInstance'是'de.package.NrGiver',他只是將它作爲一個接口投入使用.. – Ryan

+0

@Ryan ..我不知道我是在什麼程度..但是閱讀這個..http:// developer .android.com/reference/java/lang/Class.html#newInstance() – ngesh

+0

第2行是NrGiver的一個類,它實現了Interface IGiver。在我加載NrGiver類並嘗試創建一個新實例之後。但這裏整個事情失敗我不知道爲什麼 – Neon

0

不確定爲什麼使用類加載器。如果同時加載IGiver和NrGiver:

Class k = NrGiver.class; 
IGiver g = (IGiver)k.newInstance(); 
+0

我想建立一個可以管理插件的應用程序。所以我定義了Interface IGiver並需要加載稍後添加的類。所以我需要將其轉換爲對象NrGiver的IGiver界面。 – Neon