package com.logicbig.example.method;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import java.lang.reflect.Method;
import java.util.Arrays;
public class GetAnnotationsByTypeExample {
private static class Test {
@Deprecated
@Async
public void process() {
}
}
public static void main(String... args) throws NoSuchMethodException {
Method m = Test.class.getMethod("process");
Async[] a = m.getAnnotationsByType(Async.class);
System.out.println(a.length);
Arrays.stream(a).forEach(System.out::println);
}
@Target({ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
private @interface Async {}
}
Output
1
@com.logicbig.example.method.GetAnnotationsByTypeExample$Async()
package com.logicbig.example.method;
import java.lang.annotation.Repeatable;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.reflect.Method;
import java.util.Arrays;
public class GetAnnotationsByTypeExample2 {
private static class Test {
@Access("Admin")
@Access("Super User")
private void process() {}
}
public static void main(String... args) throws NoSuchMethodException {
Method m = Test.class.getDeclaredMethod("process");
Access[] a = m.getAnnotationsByType(Access.class);
System.out.println(Arrays.toString(a));
Access[] a2 = m.getDeclaredAnnotationsByType(Access.class);//no difference
System.out.println(Arrays.toString(a2));
Access a3 = m.getAnnotation(Access.class);
System.out.println(a3);
}
@Retention(RetentionPolicy.RUNTIME)
@Repeatable(MultiAccess.class)
public @interface Access {
String value() default "ADMIN";
}
@Retention(RetentionPolicy.RUNTIME)
public @interface MultiAccess {
Access[] value() default @Access;
}
}
Output
[@com.logicbig.example.method.GetAnnotationsByTypeExample2$Access(value="Admin"), @com.logicbig.example.method.GetAnnotationsByTypeExample2$Access(value="Super User")]
[@com.logicbig.example.method.GetAnnotationsByTypeExample2$Access(value="Admin"), @com.logicbig.example.method.GetAnnotationsByTypeExample2$Access(value="Super User")]
null