java - 对于 N = 1 的情况,以兼容方式进行相同类型的多个注释

标签 java annotations java-8

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

相关文章:

java - Class#isAnnotationPresent 不起作用

java - Dagger 2 - 构造函数注入(inject) - 作用域

java - 非短路逻辑运算符存在的原因

java - 在方法内设置自定义注释?

java - 大写和修剪字符串的注释

java - 如何使用 DateTimeFormatter 解析带冒号的偏移量?

java - 当键/值映射函数具有共同的计算步骤时,将 Stream 转换为 Map

Java 8 如何处理属性为 null 的情况

javax.servlet.ServletException : bean [name] not found within scope

Java 的 native Swing Web 浏览器