Returns
this element's annotation(s) for the specified type if such annotations are either directly present or indirectly
present.
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 GetDeclaredAnnotationsByTypeExample {
private static class Test {
@Deprecated
@Async
public void process() {
}
}
public static void main(String... args) throws NoSuchMethodException {
Method m = Test.class.getDeclaredMethod("process");
Async[] a = m.getDeclaredAnnotationsByType(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.GetDeclaredAnnotationsByTypeExample$Async()
package com.logicbig.example.method;
import java.lang.annotation.*;
import java.lang.reflect.Method;
import java.util.Arrays;
public class GetDeclaredAnnotationsByTypeExample2 {
private static class Test {
@Access("SUPER_USER")
@Access("CUSTOMER")
public void process() {
}
}
public static void main(String... args) throws NoSuchMethodException {
Method m = Test.class.getDeclaredMethod("process");
Access[] a = m.getDeclaredAnnotationsByType(Access.class);
System.out.println(a.length);
Arrays.stream(a).forEach(System.out::println);
System.out.println("------");
Access[] a2 = m.getDeclaredAnnotationsByType(Access.class);
System.out.println(a2.length);
Arrays.stream(a2).forEach(System.out::println);
System.out.println("------");
Access a3 = m.getAnnotation(Access.class);
System.out.println(a3);
}
@Target({ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
@Repeatable(MultiAccess.class)
public @interface Access {
String value() default "ADMIN";
}
@Target({ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
public @interface MultiAccess {
Access[] value() default @Access;
}
}
Output
2
@com.logicbig.example.method.GetDeclaredAnnotationsByTypeExample2$Access(value="SUPER_USER")
@com.logicbig.example.method.GetDeclaredAnnotationsByTypeExample2$Access(value="CUSTOMER")
------
2
@com.logicbig.example.method.GetDeclaredAnnotationsByTypeExample2$Access(value="SUPER_USER")
@com.logicbig.example.method.GetDeclaredAnnotationsByTypeExample2$Access(value="CUSTOMER")
------
null