Skip to content
Advertisement

Is it possible to cast a retrieved Class object (via reflection) to an interface?

I have 3 projects in my workspace – A, B, and C which is an Android lib project.

  1. A contains an Activity named Atest
  2. B contains a class named Btest which implements interface I.
  3. C contains the I interface.

Both A and B are installed on my Android device. During Atest runtime, i’m executing the next code:

Context otherContext = createPackageContext("com.package.b",
                CONTEXT_INCLUDE_CODE | CONTEXT_IGNORE_SECURITY);
ClassLoader loader = otherContext.getClassLoader();
Class<?> btest = Class.forName("com.package.b.BTest", true, loader);

Now here is my question – is there any way to cast btest into I within A run context?

I’ve tried many obvious (and several not-so-obvious) tricks, and nothing worked for me. I can of-course explore btest’s methods and interfaces, invoke its methods, etc.. but I simply can’t cast it into I, although both A and B referring the exact same I interface in lib-project C.

Thanks in advance!

P.S.

Kindly note that I’m casting it into an interface, not into an object, so I guess different ClassLoader isn’t the reason in this case.

Advertisement

Answer

Because you are doing all of this dynamic loading at run time there is no construction of a virtual method table and its associated vpointers. Therefore there no way for the runtime to dynamically dispatch calls to the interface methods to the appropriately loaded implementation. You have to use reflection.

User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement