Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/327.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 对于N=1的情况,同一类型以兼容方式提供多个注释_Java_Annotations_Java 8 - Fatal编程技术网

Java 对于N=1的情况,同一类型以兼容方式提供多个注释

Java 对于N=1的情况,同一类型以兼容方式提供多个注释,java,annotations,java-8,Java,Annotations,Java 8,Java8允许在注释的帮助下在同一个元素上使用多个相同类型的注释 不幸的是,他们显然忘记了支持一个注释的相应功能: import java.lang.annotation.Inherited; import java.lang.annotation.Repeatable; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.util.Objects; pu

Java8允许在注释的帮助下在同一个元素上使用多个相同类型的注释

不幸的是,他们显然忘记了支持一个注释的相应功能:

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
设置
布尔
参数,以便以相同的方式处理单例注释?

您可以在两种情况下使用:

此方法与
AnnotatedElement.getAnnotation(Class)
之间的区别在于,此方法检测其参数是否为可重复的注释类型(JLS 9.6),如果是,则尝试通过“查看”容器注释来查找该类型的一个或多个注释

修订示例:

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)]