Java 8: Repeatable Annotations


In Java 8 introduced repeatable annotation so that same annotation can be used multiple time on the same declaration and type use. For example, create a custom annotation to implement as repeatable annotation.

Pre-Requisite : Java: Annotations Tutorial

See also: Java 8: Reflection API to get Repeatable Annotation Detail

Create Custom Repeatable Annotation

import java.lang.annotation.Repeatable;
@Repeatable(Schedules.class)
public @interface Schedule {
String dayOfMonth() default "first";
String dayOfWeek() default "Mon";
int hour() default 2;
}

Create an array of repeatable annotation


package com.common.annotations;
public @interface Schedules {
Schedule[] value();
}

Use of repeatable annotation


package com.common.annotations;
import java.util.Date;
public class RepeatableAnnotationExample {
    public static void main(String[] args) {

    } 

@Schedule(dayOfMonth="last")
@Schedule(dayOfWeek="Fri", hour=23)
   public void doPeriodicCleanup() {
     System.out.println("Clean up started at :"+new Date());
   }
}

Leave a Reply

Please log in using one of these methods to post your comment:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s