@Repeatable元注解的使用


@Repeatable注解表明標記的注解可以多次應用於相同的聲明或類型,此注解由Java SE 8版本引入。以下示例如何使用此注解:

第一步,先聲明一個重復注解類:

package org.springmorning.demo.javabase.annotation.meta;

import java.lang.annotation.Repeatable;

/**
 * @author 春晨
 * @date 2019/1/14 20:25
 * Copyright ©2019 春晨 https://www.cnblogs.com/springmorning/p/10279083.html
 */
@Repeatable(Schedules.class)
public @interface Schedule {
    String dayOfMonth() default "first";
    String dayOfWeek() default "Mon";
    int hour() default 12;
}

第二步,再聲明一個容器注解類:

package org.springmorning.demo.javabase.annotation.meta;

import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;

/**
 * @author 春晨
 * @date 2019/1/14 20:26
 * Copyright ©2019 春晨 https://www.cnblogs.com/springmorning/p/10279083.html
 */
@Retention(RetentionPolicy.RUNTIME)
public @interface Schedules {
    Schedule[] value();
}

最后,創建一個測試類:

package org.springmorning.demo.javabase.annotation.meta;

import java.lang.reflect.Method;

/**
 * @author 春晨
 * @date 2019/1/14 20:27
 * Copyright ©2019 春晨 https://www.cnblogs.com/springmorning/p/10279083.html
 */
@Schedule(dayOfMonth="last")
@Schedule(dayOfWeek="Wed", hour=24)
public class RepetableAnnotation{

    @Schedule(dayOfMonth="last")
    @Schedule(dayOfWeek="Fri", hour=23)
    public void doPeriodicCleanup(){}

    public static void main(String[] args) throws NoSuchMethodException {

        Method doPeriodicCleanup = RepetableAnnotation.class.getMethod("doPeriodicCleanup");

        Schedules schedules = doPeriodicCleanup.getAnnotation(Schedules.class);
        System.out.println("獲取標記方法上的重復注解:");
        for (Schedule schedule: schedules.value()){
            System.out.println(schedule);
        }

        System.out.println("獲取標記類上的重復注解:");
        if (RepetableAnnotation.class.isAnnotationPresent(Schedules.class)){
            schedules = RepetableAnnotation.class.getAnnotation(Schedules.class);
            for (Schedule schedule: schedules.value()){
                System.out.println(schedule);
            }
        }

    }
}

運行結果:

獲取標記方法上的重復注解:
@org.springmorning.demo.javabase.annotation.meta.Schedule(hour=12, dayOfMonth=last, dayOfWeek=Mon)
@org.springmorning.demo.javabase.annotation.meta.Schedule(hour=23, dayOfMonth=first, dayOfWeek=Fri)
獲取標記類上的重復注解:
@org.springmorning.demo.javabase.annotation.meta.Schedule(hour=12, dayOfMonth=last, dayOfWeek=Mon)
@org.springmorning.demo.javabase.annotation.meta.Schedule(hour=24, dayOfMonth=first, dayOfWeek=Wed)

 下節繼續

    下節將給大家講解預定義注解@Override的使用

 

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM