开发者

Reflection Proxy- Visibility from class loader problem

I'm attempting to:

1) Load an interface and implementation class from a given file location

2) Create a Proxy object with reflection that matches the interface, and directs all calls to 开发者_Go百科the implementation class

This is later used for testing purposes using JUnit.

The Problem:

However, I seem to be having problems when I try to create the proxy object. I get the exception:

java.lang.IllegalArgumentException: interface Testing.Testable is not visible from class loader
...at Core.ProxyFactory.createProxy(ProxyFactory.java:26)

The line in question is as follows:

Object obj = Proxy.newProxyInstance(implementationClass.getClassLoader(), new Class[]{interfaceClass}, forwarder);

Class loading the right way?

I am loading the classes that I need using a URLClassLoader. The snippet for this is as follows:

URL url = new File(path).toURI().toURL();
URL[] urlList = {url};
// Create loader and load
ClassLoader classLoader = new URLClassLoader(urlList);
Class loadedClass = classLoader.loadClass (classname);
return loadedClass;

However, is this correct? This snippet gets repeated for each class file, and so I believe each time a new class loader is created. Could this be causing my problem? How can I resolve this?

Thanks in advance for any help you can give


Solved...
I was correct in my concerns that I was loading the classes in the wrong way. Because the classes depend on each other (e.g. one class uses another), they need to belong to the same classloader, or a child therefore of.

This problem can be solved by replacing use of the URLClassLoader with:

ClassLoader classLoader = new URLClassLoader(urlList);
Class[] classes = new Class[classNames.length];
for (int i = 0; i<classNames.length; i++) {
  classes[i] = classLoader.loadClass(classNames[i]);
}

This allows you to load multiple classes using the same classloader, and seems to solve the problem!

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜