【发布时间】:2018-01-10 14:41:13
【问题描述】:
我有一个注释定义如下:
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface CustomAnnotation {
String message();
}
我在如下界面(不是方法)上使用它:
@CustomAnnotation (message = "Testing")
public interface SomeInterface {
}
如何获取上述界面的注解?
从 Spring 框架调用 clazz.getAnnotations()、clazz.getDeclaredAnnotations() 和 AnnotationUtils.findAnnotation(),但它们都没有获取注释。以上所有方法都返回null。
是否真的可以从接口获取注释?
编辑 1:
- 自定义注释位于 jar 文件中。
- 注解的接口在当前项目中。
-
下面是扫描所有带有自定义注解的接口的代码:
Reflections reflections = new Reflections("bacePackage");Set<Class<? extends BaseInterface>> classes = reflections.getSubTypesOf(BaseInterface.class); for (Class<? extends BaseInterface> aClass : classes) { for (final Annotation annotation : aClass.getDeclaredAnnotations()) { if(annotation.annotationType() == CustomAnnotation.class) { CustomAnnotation customAnnotation = (CustomAnnotation) annotation; System.out.println(customAnnotation.message()); } } }
如果扫描注释的代码在当前项目中,那么它可以正常工作。但如果该代码在 jar 文件中,则它不会读取注释。
【问题讨论】:
-
据我记得你必须得到
beanDefinition并且只有在此调用方法之后才能检索注释。 -
看here
-
所有这些方法都应该可以工作,除非注释在运行时以某种方式从接口中删除,但这只有通过一些代码检测才能实现。
-
你能显示更多代码吗?可能是 Spring 在您的接口周围返回了某种缺少此注释的代理。然后你可以试试 clazz.getSuperClass().getAnnotation(CustomAnnotation .clazz)。
-
SomeInterface.class.getAnnotations()[0].getAnnotationType()会给CustomAnnotation
标签: java spring annotations