package com.logicbig.example.field;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import java.lang.reflect.Field;
import java.util.Arrays;
public class GetAnnotationsByTypeExample {
@MultipleOf(3)
private int anInt;
public static void main(String... args) throws NoSuchFieldException {
Field field = GetAnnotationsByTypeExample.class.getDeclaredField("anInt");
MultipleOf[] annotations = field.getAnnotationsByType(MultipleOf.class);
System.out.println(Arrays.toString(annotations));
//no difference in output because our annotation is not Repeatable
MultipleOf annotation = field.getAnnotation(MultipleOf.class);
System.out.println(annotation);
}
@Target({ElementType.FIELD})
@Retention(RetentionPolicy.RUNTIME)
private @interface MultipleOf {
int value() default 1;
}
}
Output
[@com.logicbig.example.field.GetAnnotationsByTypeExample$MultipleOf(value=3)]
@com.logicbig.example.field.GetAnnotationsByTypeExample$MultipleOf(value=3)
package com.logicbig.example.field;
import java.lang.annotation.*;
import java.lang.reflect.Field;
import java.util.Arrays;
public class GetAnnotationsByTypeExample2 {
@MultipleOf(3)
@MultipleOf(5)
private int anInt;
public static void main(String... args) throws NoSuchFieldException {
Field field = GetAnnotationsByTypeExample2.class.getDeclaredField("anInt");
MultipleOf[] annotations = field.getAnnotationsByType(MultipleOf.class);
System.out.println(Arrays.toString(annotations));
//does not work:
MultipleOf annotation = field.getAnnotation(MultipleOf.class);
System.out.println(annotation);
//try the container annotation
System.out.println("-- Using the container annotation --");
CompositeFactorOf[] annotations2 = field.getAnnotationsByType(CompositeFactorOf.class);
System.out.println(Arrays.toString(annotations2));
CompositeFactorOf annotation2 = field.getAnnotation(CompositeFactorOf.class);
System.out.println(annotation2);
}
@Target({ElementType.FIELD})
@Retention(RetentionPolicy.RUNTIME)
@Repeatable(CompositeFactorOf.class)
@interface MultipleOf {
int value();
}
@Target({ElementType.FIELD})
@Retention(RetentionPolicy.RUNTIME)
@interface CompositeFactorOf {
MultipleOf[] value();
}
}
Output
[@com.logicbig.example.field.GetAnnotationsByTypeExample2$MultipleOf(value=3), @com.logicbig.example.field.GetAnnotationsByTypeExample2$MultipleOf(value=5)]
null
-- Using the container annotation --
[@com.logicbig.example.field.GetAnnotationsByTypeExample2$CompositeFactorOf(value={@com.logicbig.example.field.GetAnnotationsByTypeExample2$MultipleOf(value=3), @com.logicbig.example.field.GetAnnotationsByTypeExample2$MultipleOf(value=5)})]
@com.logicbig.example.field.GetAnnotationsByTypeExample2$CompositeFactorOf(value={@com.logicbig.example.field.GetAnnotationsByTypeExample2$MultipleOf(value=3), @com.logicbig.example.field.GetAnnotationsByTypeExample2$MultipleOf(value=5)})