Java8新特性之重复注解

允许在同一类,属性,或方法多次使用同一个注解。
java8之前也可以重复注解,但代码可读性不好,如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
public @interface Authority {
     String role();
}

public @interface Authorities {
    Authority[] value();
}

public class RepeatAnnotationUseOldVersion {

    @Authorities({@Authority(role="Admin"),@Authority(role="Manager")})
    public void doSomeThing(){
    }
}

java8实现重复注解方式如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
@Repeatable(Authorities.class)
public @interface Authority {
     String role();
}

public @interface Authorities {
    Authority[] value();
}

public class RepeatAnnotationUseNewVersion {
    @Authority(role="Admin")
    @Authority(role="Manager")
    public void doSomeThing(){ }
}

java8创建重复注解Authority时,加上@Repeatable,指向存储注解Authorities,在使用时候,直接可以重复使用Authority注解,java8实现方式可读性比之前强。