kag*_*ag0 6 java reflection annotations classloader kotlin
我正在尝试从方法中获取注释,但遇到了一些麻烦。我正在做的是使用 URLClassLoader 加载 jar 文件,然后使用反射和 Method.getAnnotation 检查该 jar 中类中方法的注释。
我遇到的问题是 Method.getAnnotation 将始终返回 null,即使注释存在(我们可以使用 Method.getAnnotations 看到)。我已经在未使用 URLClassLoader 加载的类上的相同注释类型上测试了相同的过程,并且工作正常。
更深入的调查表明,instance.annotationType() 和 MyAnnotation.class 的规范名称是相同的。但是,instance.annotationType().equals(MyAnnotation.class) 返回 false。然而,实例本身是一个代理 (com.sun.proxy)。
有没有一种方法可以在不进行大量反射的情况下获取注释和注释的字段?
instance.annotationType().getMethod("value").invoke(instance)
Run Code Online (Sandbox Code Playgroud)
上面的方法可以获取该字段,并且通过对规范名称进行字符串比较来迭代 Method.getAnnotations 的结果将为我提供注释,但肯定有更好的方法吗?
也为了教育价值,是什么原因造成的?我的猜测是,这是因为系统类加载器加载的注释的类与 URL 类加载器加载的注释的类在某种程度上不同。
一个 hacky 解决方案如下:
而不是 AccessibleObject.getAnnotation(Class commentClass) 使用
private static Annotation getAnnotation(AccessibleObject object, Class annotationClass){
for(Annotation a : object.getAnnotations()){
if(a.annotationType().getCanonicalName().equals(annotationClass.getCanonicalName()))
return a;
}
return null;
}
Run Code Online (Sandbox Code Playgroud)
而不是 MyAnnotation.value() 使用
private static Object getAnnotationFieldWithReflection(Annotation annotation, String fieldName) throws NoSuchMethodException, InvocationTargetException, IllegalAccessException {
return annotation.annotationType().getMethod(fieldName).invoke(annotation);
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2351 次 |
| 最近记录: |