Search code examples
javaclassloader

How to access an object instance loaded by the other classloader exception for using reflection?


I'm confused that how an object instance loaded by the other classloader can be accessed without the ClassCastExcepion being thrown except for using reflection? It seems that using JndiObjectFactoryBean is a better idea,but I donot understand. Is there anyone Can make me clear? Thanks very much.


Solution

  • The only way (apart from reflection) is to always use an interface type to interact with the class; e.g.

    public interface I {
        public void foo();
    }
    
    public class C implements I {
        public void foo(){ ... }
    }
    
    ...
    Classloader l1 = ...
    I c1 = (I) l1.loadClass("some.pkg.C").newInstance();
    c1.foo();
    
    Classloader l2 = ...
    I c2 = (I) l2.loadClass("some.pkg.C").newInstance();
    c2.foo();
    

    The interface I must loaded by a common ancestor classloader of l1 and l2. And assuming that these classloaders (l1 and l2) actually loaded the classes, you cannot cast either c1 or c2 to C.