title: Cast object to interface when created via reflection
body: <p>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.</p>
  
  <p>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:</p>
  
  <pre><code>PackageManager pm = getPackageManager();
  List&lt;ResolveInfo&gt; lr = pm.queryIntentServices(new Intent("com.example.some.action"), 0);
  ArrayList&lt;MyInterface&gt; list = new ArrayList&lt;MyInterface&gt;();
  
  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&lt;?&gt; 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();
      }
  }
  </code></pre>