使用代理时,类加载器看不到接口? [英] Interface is not visible from ClassLoader when using a proxy?

查看:22
本文介绍了使用代理时,类加载器看不到接口?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我尝试使用动态代理时,我看到以下异常

I am seeing following exception when I try to use dynamic proxy

 com.intellij.rt.execution.application.AppMain DynamicProxy.DynamicProxy
Exception in thread "main" java.lang.IllegalArgumentException: interface Interfaces.IPerson is not visible from class loader
    at java.lang.reflect.Proxy.getProxyClass(Proxy.java:353)
    at java.lang.reflect.Proxy.newProxyInstance(Proxy.java:581)
    at DynamicProxy.Creator.getProxy(Creator.java:18)
    at DynamicProxy.DynamicProxy.main(DynamicProxy.java:54)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)

知道我需要做什么来解决它

Any idea what I need to do to resolve it

推荐答案

如果这是 Web 应用程序,那么在创建动态代理时应该使用 Web 应用程序类加载器.因此,例如,而不是:

If this is web application, then you should use the web application classloader when creating dynamic proxy. So, for example instead of:

Proxy.newProxyInstance(
  ClassLoader.getSystemClassLoader(),
  new Class < ? >[] {MyInterface.class},
  new InvocationHandler() {
    // (...)
});

试试:

Proxy.newProxyInstance(
  this.getClass().getClassLoader(), // here is the trick
  new Class < ? >[] {MyInterface.class},
  new InvocationHandler() {
    // (...)
});

例如,tomcat 类加载器的层次结构(其他 Web 容器也类似)如下:

For instance, hierarchy of tomcat class loaders (other web containers have similar) is following:

      Bootstrap
          |
       System
          |
       Common
       /     
  Webapp1   Webapp2 ... 

它是 webapp 类加载器,它包含 Web 应用程序/WEB-INF/classes 目录中的类和资源,以及 Web 应用程序/WEB-INF/lib 目录下 JAR 文件中的类和资源.

And it is the webapp classloader which contains classes and resources in the /WEB-INF/classes directory of your web application, plus classes and resources in JAR files under the /WEB-INF/lib directory of your web application.

这篇关于使用代理时,类加载器看不到接口?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆