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());
   }
}
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

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

Google photo

You are commenting using your Google 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