在 @Repeatable
的帮助下,Java 8 允许在同一元素上使用相同类型的多个注释。注释。
不幸的是,他们显然忘记了支持一个注释情况的相应功能:
import java.lang.annotation.Inherited;
import java.lang.annotation.Repeatable;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.util.Objects;
public class MultipleAnnotationsCompatibility {
@Inherited
@Retention(RetentionPolicy.RUNTIME)
public @interface FileTypes {
FileType[] value();
}
@Inherited
@Repeatable(FileTypes.class)
@Retention(RetentionPolicy.RUNTIME)
public @interface FileType {
String value();
}
@FileType("png")
@FileType("jpg")
public static class Image {
}
@FileType("xls")
public static class Worksheet {
}
public static void main(String[] args) {
FileTypes fileTypes;
fileTypes = Image.class.getAnnotation(FileTypes.class);
System.out.println("fileTypes for Image = " + Objects.toString(fileTypes));
fileTypes = Worksheet.class.getAnnotation(FileTypes.class);
System.out.println("fileTypes for Worksheet = " + Objects.toString(fileTypes));
}
}
第二个 println
输出 null
,尽管事实上这些情况之间没有逻辑差异。
有没有办法用相同的代码处理1个和2个以上注释的情况?
他们可能应该为 @Repeatable
创建 boolean
参数,以同样的方式处理单例注释?
最佳答案
您可以使用Class::getAnnotationsByType
在这两种情况下:
The difference between this method and
AnnotatedElement.getAnnotation(Class)
is that this method detects if its argument is a repeatable annotation type (JLS 9.6), and if so, attempts to find one or more annotations of that type by "looking through" a container annotation.
修改后的示例:
FileType[] fileTypes;
fileTypes = Image.class.getAnnotationsByType(FileType.class);
System.out.println("fileTypes for Image = " + Arrays.toString(fileTypes));
fileTypes = Worksheet.class.getAnnotationsByType(FileType.class);
System.out.println("fileTypes for Worksheet = " + Arrays.toString(fileTypes));
输出:
fileTypes for Image = [@abc$FileType(value=png), @abc$FileType(value=jpg)]
fileTypes for Worksheet = [@abc$FileType(value=xls)]
关于java - 对于 N = 1 的情况,以兼容方式进行相同类型的多个注释,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33764003/