Interface is not visible from ClassLoader when using a proxy?

前端 未结 3 657
面向向阳花
面向向阳花 2020-12-31 07:45

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

 com.intellij.rt.execution.application.AppMain DynamicProxy.DynamicProxy
Exception in thread         


        
3条回答
  •  旧时难觅i
    2020-12-31 08:01

    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() {
        // (...)
    });
    

    try:

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

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

          Bootstrap
              |
           System
              |
           Common
           /     \
      Webapp1   Webapp2 ... 
    

    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.

提交回复
热议问题