【问题标题】:How to get annotation from interface如何从界面获取注释
【发布时间】: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:

  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());
            }
        }
    }
    

如果扫描注释的代码在当前项目中,那么它可以正常工作。但如果该代码在 jar 文件中,则它不会读取注释。

【问题讨论】:

  • 据我记得你必须得到beanDefinition 并且只有在此调用方法之后才能检索注释。
  • here
  • 所有这些方法都应该可以工作,除非注释在运行时以某种方式从接口中删除,但这只有通过一些代码检测才能实现。
  • 你能显示更多代码吗?可能是 Spring 在您的接口周围返回了某种缺少此注释的代理。然后你可以试试 clazz.getSuperClass().getAnnotation(CustomAnnotation .clazz)。
  • SomeInterface.class.getAnnotations()[0].getAnnotationType() 会给CustomAnnotation

标签: java spring annotations


【解决方案1】:

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

【讨论】:

  • 不涉及超类。注解放置在一个接口上,该接口没有任何实现。
【解决方案2】:

SomeInterface.class.getAnnotations()[0].getAnnotationType().getName()
将为您提供完全限定的名称。

我使用 [0] 因为我知道只有一个注解。如果有很多注释,您可能需要更改它或遍历所有注释

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-02-14
    • 2011-08-31
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多