反射代理 - 类加载器问题的可见性
我正在尝试:
1) 从给定文件位置加载接口和实现类
2) 创建一个具有与接口匹配的反射的 Proxy 对象,并将所有调用定向到实现类
这稍后将用于使用 JUnit 进行测试。
问题:
但是,当我尝试创建代理对象时似乎遇到了问题。我收到异常:
java.lang.IllegalArgumentException: interface Testing.Testable is not visible from class loader
...at Core.ProxyFactory.createProxy(ProxyFactory.java:26)
有问题的行如下:
Object obj = Proxy.newProxyInstance(implementationClass.getClassLoader(), new Class[]{interfaceClass}, forwarder);
类加载方式正确吗?
我正在使用 URLClassLoader 加载所需的类。其片段如下:
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;
但是,这是正确的吗?对于每个类文件都会重复此片段,因此我相信每次创建新的类加载器时。这会导致我的问题吗?我该如何解决这个问题?
提前感谢您提供的任何帮助
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 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
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
已解决...
我对我以错误的方式加载类的担忧是正确的。因为这些类相互依赖(例如,一个类使用另一个类),所以它们需要属于同一个类加载器,或其子类加载器。
这个问题可以通过将 URLClassLoader 的使用替换为来解决:
这允许您使用相同的类加载器加载多个类,并且似乎可以解决问题!
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:
This allows you to load multiple classes using the same classloader, and seems to solve the problem!