URLClassLoader 将 Annotation 加载为 com.sun.$Proxy$27 [英] URLClassLoader loads Annotation as com.sun.$Proxy$27

查看:24
本文介绍了URLClassLoader 将 Annotation 加载为 com.sun.$Proxy$27的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试动态加载 Java 类.基本思想是,jar 包含在运行时动态加载的模块.这就是我的做法(我知道这很笨拙,但没有其他方法可以将 jar 动态添加到已经存在的类加载器 afaik):

I'm trying to dynamically load a java class. The basic idea is, that a jar contains modules which get loaded dynamically at runtime. This is how I do it (I know it's hacky, but there is no other method to dynamically add a jar to an already existing classloader afaik):

Method method = URLClassLoader.class.getDeclaredMethod("addURL", new Class[] { URL.class });
method.setAccessible(true);
method.invoke(moduleLoader, new Object[] { file.toURI().toURL() });
Class fooClass = moduleLoader.loadClass("com.coderunner.Foo");
Object foo = fooClass.newInstance();

每个模块都使用@Module 注释进行注释.因此,为了获得有关该模块的更多信息,我尝试获取注释.问题是 foo 上的注释的类型是 com.sun.$Proxy$27 而不是 com.coderunner.Module,因此我得到一个

Every module is annotated with an @Module annotation. So in order to gain further informations about the module, I try to get the annotation. The problem is that the annotation on foo is of type com.sun.$Proxy$27 instead of com.coderunner.Module and therefore I get a

ClassCastException: Cannot cast com.sun.proxy.$Proxy42 (id=64) to com.coderunner.Module

我不得不说我对这里发生的事情感到有些困惑.我想做的可能吗?怎么样?

I have to say I'm a bit confused what happens here. Is what I want to do possible? How?

我也许还应该提到我正在 spring/spring-mvc 和 tomcat 环境中尝试这个.

I maybe also should mention I'm trying this in a spring/spring-mvc and tomcat environment.

推荐答案

在注解类型前面获得代理的事实应该无关紧要.它实际上可能会误导您相信这是导致您遇到问题的原因.如果诸如isAnnotationPresent(..)"之类的内容失败,则不是由于该代理,而是因为您使用多个类加载器多次加载了注释类.例如,Jetty 默认优先考虑 WebApp 类加载器.因此,如果您的 Jetty 服务器实例(或 Tomcat 或其他)已经加载了注释类,并且该注释也在您的 WebApp 的类路径上,那么您可能会遇到诸如getAnnotation()"之类的问题不返回任何内容.只需确保包含您的注释的库没有被加载两次.

The fact that you get a proxy in front of your annotation type should not matter. It might actually mislead you into believing that this is the cause for problems you are having. If stuff like "isAnnotationPresent(..)" fails, it is not due to that proxy, it is because you have loaded the annotation class multiple times using multiple classloaders. For example, Jetty gives priority to the WebApp classloader by default. So if your Jetty server instance (or Tomcat or whatever) already has loaded the annotation class, and the annotation is on your WebApp's classpath, too, you can have problems like "getAnnotation()" not returning anything. Just make sure that the library containing your annotation is not loaded twice.

Andreas 提供的解决方案是一个非常肮脏的解决方法,只是掩盖了您可能没有控制/正确组织类加载的事实.

The solution provided by Andreas is, well, a very dirty workaround and just covers up the fact that you probably don't have your classloading under control/properly organized.

这篇关于URLClassLoader 将 Annotation 加载为 com.sun.$Proxy$27的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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