views:

27

answers:

1

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.

+2  A: 

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.

Stephen C
Thanks for your reply.I use JndiObjectFactoryBean to get a service instance which is bound by the other web application, and I directly cast the instance which is proxyed by JndiObjectFactoryBean to the type, it works well and no ClassCastException being thrown.How do JndiObjectFactoryBean work?Using the proxy can solve this?
SuoNayi
I don't know whether a proxy would help in this case. Why don't you try it?
Stephen C