被元注解@Repeatable修饰的注解,可以在同一个地方使用多次。这是JAVA8加入的新特性,在此之前注解在同一个地方只能使用一次(实际上有解决方案,但可读性不好)。
@Repeatable的使用有以下几个要点:
-
在需要重复使用的注解上修饰 @Repeatable
-
@Repeatable中的参数为被修饰注解的容器的类对象(class对象)
-
容器包含一个value方法,返回一个被修饰注解的数组
这样就完成了一个可重复使用的注解的定义,然后在对应类、方法、属性上多次使用该注解,并通过反射的方法获取注解数组,根据需要获取数据。
import static java.lang.annotation.ElementType.METHOD;
import java.lang.annotation.Repeatable;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
public class FindFiles {
@Target( METHOD)
@Retention( RetentionPolicy.RUNTIME )
public @interface FileTypes {
FileType[] value();//对应3
}
@Target( METHOD )
@Retention( RetentionPolicy.RUNTIME )
@Repeatable( FileTypes.class )//对应1、2
public @interface FileType {
String value();
};
@FileType( ".java" )
@FileType( ".html" )
@FileType( ".css" )
@FileType( ".js" )
public void work(){
try {
FileType[] fileTypes= this.getClass().getMethod("work").getAnnotationsByType(FileType.class);
System.out.println("将从如下后缀名的文件中查找文件内容");
for (FileType fileType : fileTypes) {
System.out.println(fileType.value());
}
System.out.println("查找过程略。。。");
} catch (NoSuchMethodException | SecurityException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public static void main(String[] args) {
new FindFiles().work();
}
}
其中FileType就是要重复使用的注解,FileTypes是容器。