[英]Android ,Interface ,new Instance
i have a problem with a newInstance call using Reflection in Android. 我在Android中使用Reflection遇到newInstance调用时遇到问题。
My Interface: 我的界面:
public interface IGiver {
public int getNr();
}
My Class to call Reflection: 我的班级叫反思:
public class NrGiver implements IGiver {
int i = 10;
@Override
public int getNr() {
return i;
}
}
The way i try to call getNr: 我尝试致电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();
The last line wont work it cause an Error and my App stops. 最后一行不起作用,它会导致错误,并且我的应用程序停止。 I know it fault of newInstance, but i want to work on the IGiver object.
我知道是newInstance的错,但我想在IGiver对象上工作。
Pls Help me. 请帮助我。
My Solution: 我的解决方案:
Hey guys finally i got the chicken. 大家好,我终于得到了鸡肉。
I found an other way. 我找到了另一种方式。 this time i also used newInstance, but this time its worked.
这次我也使用了newInstance,但是这次它起作用了。 My solution:
我的解决方案:
Class c = Class.forName(className);
Method methode = c.getDeclaredMethod("getNr");
Object i = methode.invoke(c.newInstance(), new Object[]{});
And this what i wanted to do. 这就是我想做的。 I have an NrGiver.class somewhere on my Phone.
我的手机上某处有一个NrGiver.class。 And it implements the Interface IGiver.
并且它实现了接口IGiver。 So it can be loaded into my App dynamically.
因此可以将其动态加载到我的App中。 I need the Integer from the class NrGiver.
我需要NrGiver类中的Integer。 So i can make my code generic.
这样我就可以使我的代码通用。 I tried to Cast the Object to my Interface, but it failed.
我试图将对象强制转换为接口,但是失败了。
So i found an other way to invoke the method of a class. 因此,我找到了另一种方法来调用类的方法。
Thx for help 寻求帮助
String className = "de.package.NrGiver";//line 1
Class c = Class.forName(className);//line 2
IGiver giver = (IGiver) c.newInstance();//line3
in line 2 forName is trying to find a class but the String is representing a Interface, so the classLoader does not find the class and it throws an exception. 第2行中的 forName试图找到一个类,但是String表示一个Interface,因此classLoader找不到该类,并且抛出异常。 adding on to it, in line 3 you are trying to get an Instance of Interface which does't exist in the
java world
.. i mean to say Interfaces cannot be instanciated and they do not have constructors. 加上它,在第3行中,您尝试获取在
java world
不存在的Interface的实例..我的意思是说,不能实例化 Interfaces并且它们没有构造函数。 . 。
not sure why is classloader used. 不知道为什么要使用classloader。 if both IGiver and NrGiver are loaded:
如果同时加载了IGiver和NrGiver:
Class k = NrGiver.class;
IGiver g = (IGiver)k.newInstance();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.