Passing an object to an interface when created through reflection

I am trying to find something in Android and I am stuck when trying to apply a class in another .apk to my interface. I have an interface and various classes in other .apks that implement this interface. I find other classes using PackageManager query methods and use Application # createPackageContext () to get the class loader for this context. Then I load the class, create a new instance and try to pass it to my interface, which, as I know, definitely implements.

When I try to throw, it throws a class exception. I tried various things, such as loading the interface first, using classC # asSubclass, etc., None of which work. Class # getInterfaces () shows that the interface is implemented. My code is below:

PackageManager pm = getPackageManager();
List<ResolveInfo> lr = pm.queryIntentServices(new Intent("com.example.some.action"), 0);
ArrayList<MyInterface> list = new ArrayList<MyInterface>();

for (ResolveInfo r : lr) {
    try {
        Context c = getApplication().createPackageContext(r.serviceInfo.packageName, Context.CONTEXT_IGNORE_SECURITY | Context.CONTEXT_INCLUDE_CODE);
        ClassLoader cl = c.getClassLoader();
        String className = r.serviceInfo.name;
        if (className != null) {
            try {
                Class<?> cls = cl.loadClass(className);
                Object o = cls.newInstance();
                if (o instanceof MyInterface) { //fails
                    list.add((MyInterface) o);
                }

            } catch (ClassNotFoundException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } // some exceptions removed for readability
        }
    } catch (NameNotFoundException e1) {
        e1.printStackTrace();
    }
}
+3
source share
1 answer

I was not involved in Android development, so I'm not sure about the nuances of my class loaders, but in general programming in Java the two classes loaded by different class loaders do not match hellip either; even if they are loaded from the same file class.

, X "" , , , , X "" , "" X .

, X , .

+3

Source: https://habr.com/ru/post/1748415/


All Articles