Java 8, introduced some new reflection APIs to retrieve annotation related information from different elements types like classes, interfaces, method, type, etc.
Reflection API provides new method getAnnotionByType() to return array of repeating annotations type.
Pre-requisite: Java: Annotations
In previous post Java 8: Repeatable Annotations you have learned about the creation and implementation of repeatable annotation. Let’s take one more example of repeatable annotation and see how to get annotation detail by Java reflection APIs.
Example: Retrieve Annotation Detail by Reflection API
As repeating annotations should themselves annotated with @Repeatable(Filetrs.class) annotation. Here Filters is just a holder of Filter’s annotations. The filterable interface defined Filter annotation two times with different values.
import java.lang.annotation.ElementType; import java.lang.annotation.Repeatable; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; public class RepeatingAnnotations { @Target(ElementType.TYPE) @Retention(RetentionPolicy.RUNTIME) public @interface Filters { Filter[] value(); } @Target(ElementType.TYPE) @Retention(RetentionPolicy.RUNTIME) @Repeatable(Filters.class) public @interface Filter { String value(); }; @Filter("filter1") @Filter("filter2") public interface Filterable { } public static void main(String[] args) { /** *Here reflection API Class.getAnnotationsByType() returns *array of applied annotations */ for (Filter filter : Filterable.class .getAnnotationsByType(Filter.class)) { System.out.println(filter.value()); } } }
Output
filter1
filter2
You must log in to post a comment.