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.
views:
27answers:
1
+2
Q:
How to access an object instance loaded by the other classloader exception for using reflection?
+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
2010-08-25 03:33:20
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
2010-08-25 04:27:19
I don't know whether a proxy would help in this case. Why don't you try it?
Stephen C
2010-08-25 04:46:23