Java 8可重复注释

时间:2016-05-27 07:39:51

标签: java annotations java-8

试图弄清楚如何与Java 8可重复注释支持相处。

以下: https://blog.idrsolutions.com/2015/03/java-8-repeating-annotation-explained-in-5-minutes/

它完美无缺。

但是,如果我修改示例并在Car类上只添加一个@Manufacturer,我就无法读取该单个注释。因此,如果重复注释只出现1次,则无法读取。

所以:

<ComboBox ItemsSource="{Binding ShiftList}"
          SelectedItem="{Binding SelectedShift}"
          ... />

此处的大小为0

@Manufacturer("Range Rover")
public class Car {

}


Manufacturer[] a = Car.class.getAnnotationsByType(Manufacturer.class );

这里将有汽车的NPE ..

为什么?

2 个答案:

答案 0 :(得分:1)

您尝试获取Cars类型的注释,而不是类型制造商。

以下解决方案有效:

    Manufacturer[] annotations = Car.class.getAnnotationsByType(Manufacturer.class);
    for (Manufacturer annotation : annotations) {
        System.out.println(annotation.name());
    }

您应该始终将注释的类型传递给getAnnotation或getAnnotationsByType,而不是类本身的类型。

希望它能帮助你

答案 1 :(得分:1)

所以问题是Manufacturer注释没有RetentionPolicy只声明容器注释(Cars)。

所以添加

@Retention(RetentionPolicy.RUNTIME)

同样在Manufacturer注释中将读取基于容器 / 基于单一方式的注释(以某种方式)

谢谢肖恩,至少你回答给了我一个线索......