如何从界面获取注释

时间:2018-01-10 14:41:14

标签: java spring annotations

我的注释定义如下:

@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:

  1. 自定义注释位于jar文件中。
  2. 带注释的界面位于当前项目中。
  3. 下面是扫描所有使用自定义注释注释的接口的代码:

    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());
            }
        }
    }
    
  4. 如果扫描注释的代码在当前项目中,则它可以正常工作。但是如果该代码在jar文件中,那么它就不会读取注释。

2 个答案:

答案 0 :(得分:0)

两种方法都应该有效。我的猜测是Spring将它包装在缺少注释的代理中。您可以尝试在超类上发现注释,例如clazz.getSuperClass()。getAnnotation(...)。或者尝试将@Inherited放在您的自定义注释上。

答案 1 :(得分:0)

SomeInterface.class.getAnnotations()[0].getAnnotationType().getName()
 会给你完全合格的名字。

我使用过[0]因为我知道只有一个注释。如果有很多

,您可能需要更改它或遍历所有注释