java遺珠之重複註解
版權宣告:本文為博主原創文章,未經博主允許不得轉載。https://blog.csdn.net/lastsweetop/article/details/82868378
重複註解
有時候你需要相同的註解在同一種類型或者定義上,這時候重複註解就發揮作用了。
我來看個定時執行的程式碼
@Component public class ScheduledTasks { private static final Logger log = LoggerFactory.getLogger(ScheduledTasks.class); private static final SimpleDateFormat dateFormat = new SimpleDateFormat("HH:mm:ss"); @Scheduled(fixedDelay = 1500) @Scheduled(fixedRate = 1000) public void reportCurrentTime() { log.info("The time is now {}", dateFormat.format(new Date())); } }
一個定時任務按照兩種規則執行,一種是一個任務執行完延遲1500ms執行另一個,另一個是1000ms執行一個任務,不管其他任務有沒有執行完畢。
因著相容的原因,重複註解被存在一個由編譯器自動生成的註解容器中,為了能讓編譯器做到如此,需要兩步操作
1.定義重複註解型別
省略一些無關的元素,註解型別必須使用@Repeatable
元註解型別,
@Repeatable(Schedules.class) public @interface Scheduled { }
在@Repeatable
的括號裡是存放註解的容器的型別,註解@Scheduled
存放在註解@Schedules
中。
2.定義包含註解的型別
包含註解的型別必須有個陣列型別的value元素,陣列的型別必須是重複註解的型別。
public @interface Schedules { Scheduled[] value(); }
檢索註解
Reflection Api中有檢索註解的api,對於重複註解需要使用AnnotatedElement.getAnnotationsByType(Class<T> annotationClass)
程式碼如下:
public static void main(String[] args) { Method[] methods = ScheduledTasks.class.getDeclaredMethods(); for (Method method : methods) { Scheduled[] scheduleds = method.getAnnotationsByType(Scheduled.class); for (Scheduled scheduled : scheduleds) { System.out.println(scheduled); } } }