Java8 新增的 @Repeatable 註解

        JDK8中新增加註解Repeatable ,今天在看《SpringBoot編程思想》中走向註解驅動編程(Annatation-Driven)這一章節中提到了這個註解,我對這個註解感到比較陌生,以前讀springboot源碼也看到了這個註解,現在就學習可以一下。

Repeatable 源代碼

package java.lang.annotation;

/**
 * The annotation type {@code java.lang.annotation.Repeatable} is
 * used to indicate that the annotation type whose declaration it
 * (meta-)annotates is <em>repeatable</em>. The value of
 * {@code @Repeatable} indicates the <em>containing annotation
 * type</em> for the repeatable annotation type.
 *
 * @since 1.8
 * @jls 9.6.3 Repeatable Annotation Types
 * @jls 9.7.5 Multiple Annotations of the Same Type
 */
@Documented
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.ANNOTATION_TYPE)
public @interface Repeatable {
    /**
     * Indicates the <em>containing annotation type</em> for the
     * repeatable annotation type.
     * @return the containing annotation type
     */
    Class<? extends Annotation> value();
}
The annotation type java.lang.annotation.Repeatable is used to indicate that 
        the annotation type whose declaration it (meta-)annotates is repeatable.
The value of @Repeatable 
        indicates the containing annotation type for the repeatable annotation type.

@Repeatable 註解用於指示它註解聲明的註解類型是可重複的。
@Repeatable 的值用於指示一個註解類型,這個註解類型用來存放可重複的註解類型。

我們先定義一個角色註解Role,這個註解用@Repeatable聲明,表示可以重複在一個類上使用@Role,而多個@Role存放在@Roles註解的value中。

@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Repeatable(Roles.class)
public @interface Role {
    String value() default "";
}
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface Roles {
    Role[] value();
}

創建兩個用戶類,並且使用Role註解標註

@Role("custom")
@Role("biz_admin")
public class BizUser {
    private String name;
}
@Role("custom")
@Role("system_admin")
public class SysUser {
    private String name;
}

測試Demo如下

public class RepeatableDemo {
    public static void main(String[] args) {
        if(SysUser.class.isAnnotationPresent(Roles.class)) {
            Roles roles = SysUser.class.getAnnotation(Roles.class);
            System.out.println("SysUser的角色如下:");
            for(Role role : roles.value())
                System.out.println(role.value());
        }

        if(BizUser.class.isAnnotationPresent(Roles.class)) {
            Roles roles = BizUser.class.getAnnotation(Roles.class);
            System.out.println("BizUser的角色如下:");
            for(Role role : roles.value())
                System.out.println(role.value());
        }
    }
}

 

@Role與@Roles的配合,Java8+如下

@Role("custom")
@Role("system_admin")
public class SysUser {
    private String name;
}

Java8之前的等效寫法如下

@Roles({
        @Role("custom"),
        @Role("system_admin")
})
public class SysUser {
    private String name;
}

 

Java編程:Java8 新增的 @Repeatable 註解

發佈了334 篇原創文章 · 獲贊 66 · 訪問量 21萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章