gpt4 book ai didi

java - URLClassLoader 将 Annotation 加载为 com.sun.$Proxy$27

转载 作者:搜寻专家 更新时间:2023-11-01 03:24:32 25 4
gpt4 key购买 nike

我正在尝试动态加载 java 类。基本思想是,一个 jar 包含在运行时动态加载的模块。这就是我的做法(我知道这很老套,但没有其他方法可以将 jar 动态添加到已经存在的类加载器 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 类型,因此我得到一个

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

我不得不说我对这里发生的事情有点困惑。我想做的事可行吗?怎么办?

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

最佳答案

反射返回代理对象的事实并不妨碍您收集有关注释及其值的信息。

getclass 方法返回一个代理对象:

 log.info("annotation class:" + annotation.getClass());

输出:

 [INFO] annotation class:class com.sun.proxy.$Proxy16class 

输出与您的示例中的相同,但这没问题。拥有方法(或字段)就足够了。附加部分是仅调用注释方法

public void analyseClass(Class myClass) {

for (Method method: myClass.getMethods()) {
System.out.println("aanotations :" + Arrays.toString(field.getAnnotations()));

for (Annotation annotation : method.getAnnotations()) {

log.info("annotation class:" + annotation.getClass());
log.info("annotation class type:" + annotation.annotationType());

Class<Annotation> type = (Class<Annotation>) annotation.annotationType();

/* extract info only for a certain annotation */
if(type.getName().equals(MyAnnotation.class.getName())) {

String annotationValue =
(String) type.getMethod("MY_ANNOTATION_CERTAIN_METHOD_NAME").invoke(annotation);

log.info("annotationValue :" + annotationValue);
break;
}
}
}

//do the same for the fields of the class
for (Field field : myClass.getFields()) {
//...
}

}

为了找到这个解决方案,我使用了以下帖子: How to get annotation class name, attribute values using reflection

关于java - URLClassLoader 将 Annotation 加载为 com.sun.$Proxy$27,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18282337/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com