Java-8 repeatable user annotations

I know about basic annotations in java like @Overrideetc.

Annotations are only metadata and they do not contain any business logic.

I will move on to repeating annotations on the oracle page to understand the new feature java-8.

For example, you are writing code to use timer service that enables you to run a method at a given time or on a certain schedule, similar to the UNIX cron service. Now you want to set a timer to start the method,, doPeriodicCleanupon the last day of the month and every Friday at 11:00. To configure the timer to run, create an annotation @Scheduleand apply it twice to the doPeriodicCleanup method.

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

Declare a duplicate annotation type

The type of annotation should be marked with the @Repeatable meta annotation. The following example defines a custom type of repeatable annotation @Schedule:

import java.lang.annotation.Repeatable;

@Repeatable(Schedules.class)
public @interface Schedule {
  String dayOfMonth() default "first";
  String dayOfWeek() default "Mon";
  int hour() default 12;
}

Declare the contained annotation type

. . , , :

public @interface Schedules {
    Schedule[] value();
}

@Schedules. ?.

public void doPeriodicCleanup() { ... }

.

+4
1

Java 8 ( , ..). , , "wrapping", Schedules, Schedule.

, , - :

@Schedules(value = {
    @Schedule(dayOfMonth="last"),
    @Schedule(dayOfWeek="Fri", hour="23")
})

, Schedules , .

, API ,

@Schedule(dayOfMonth="last"),
@Schedule(dayOfWeek="Fri", hour="23")

Schedule "wrapping". , , : "", . .

+6

All Articles