尝试弄清楚如何使用 Java 8 可重复注释支持。
以下: https://blog.idrsolutions.com/2015/03/java-8-repeating-annotation-explained-in-5-minutes/
它工作完美。
但是,如果我修改示例并在 Car 类上仅添加 @Manufacturer,我将无法读取该单个注释。因此,如果重复注释仅出现 1 次,则无法读取。
所以有:
@Manufacturer("Range Rover")
public class Car {
}
Manufacturer[] a = Car.class.getAnnotationsByType(Manufacturer.class );
此处的大小将为 0
和
Cars cars = Car.class.getAnnotation(Cars.class);
for(Manufacturer car: cars.value())
System.out.println(car.value());
这里的汽车上会有一个 NPE..
这是为什么?
最佳答案
您尝试获取汽车类型的注释,而不是制造商类型的注释。
以下解决方案有效:
Manufacturer[] annotations = Car.class.getAnnotationsByType(Manufacturer.class);
for (Manufacturer annotation : annotations) {
System.out.println(annotation.name());
}
您应该始终将注释的类型传递给 getAnnotation 或 getAnnotationsByType,而不是类本身的类型。
希望对你有帮助
关于Java 8 可重复注释,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37477593/