Cast object to interface when created via reflection

Posted by Al on Stack Overflow See other posts from Stack Overflow or by Al
Published on 2010-06-03T20:32:25Z Indexed on 2010/06/03 20:34 UTC
Read the original article Hit count: 291

Filed under:
|
|
|

I'm trying some stuff out in Android and I'm stuck at when trying to cast a class in another .apk to my interface. I have the interface and various classes in other .apks that implement that interface. I find the other classes using PackageManager's query methods and use Application#createPackageContext() to get the classloader for that context. I then load the class, create a new instance and try to cast it to my interface, which I know it definitely implements.

When I try to cast, it throws a class cast exception. I tried various things like loading the interface first, using Class#asSubclass, etc, none of which work. Class#getInterfaces() shows 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();
        }    

© Stack Overflow or respective owner

Related posts about java

Related posts about android