2011-08-18 17 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