开发者

Android ,Interface ,new Instance

开发者 https://www.devze.com 2023-03-29 04:13 出处:网络
i have a problem with a newInstance call using Reflection in Android. My Interface: public interface IGiver {

i have a problem with a newInstance call using Reflection in Android.

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:

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

S开发者_运维问答tring 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.

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. 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. And it implements the Interface IGiver. So it can be loaded into my App dynamically. I need the Integer from the class NrGiver. 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. 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..


not sure why is classloader used. if both IGiver and NrGiver are loaded:

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

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号