I have 3 projects in my workspace – A, B, and C which is an Android lib project.
- A contains an Activity named
Atest
- B contains a class named
Btest
which implements interfaceI
. - 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.