Close

Java Reflection - Method.getAnnotations() Examples

Java Reflection Java Java API 


Class:

java.lang.reflect.Method

java.lang.Objectjava.lang.Objectjava.lang.reflect.AccessibleObjectjava.lang.reflect.AccessibleObjectjava.lang.reflect.AnnotatedElementAnnotatedElementjava.lang.reflect.Executablejava.lang.reflect.Executablejava.lang.reflect.MemberMemberjava.lang.reflect.GenericDeclarationGenericDeclarationjava.lang.reflect.Methodjava.lang.reflect.MethodLogicBig

Method:

public Annotation[] getAnnotations()

This method returns annotations that are present on this method. If there are no annotations present, the return value is an array of length 0.


Examples


package com.logicbig.example.method;

import java.lang.annotation.*;
import java.lang.reflect.Method;
import java.util.Arrays;

public class GetAnnotationsExample {
private static class Test{
@Deprecated
@Async
public void process() {
}
}

public static void main(String... args) throws NoSuchMethodException {
Method m = Test.class.getDeclaredMethod("process");
Annotation[] a = m.getAnnotations();
System.out.println(a.length);
Arrays.stream(a).forEach(System.out::println);
}


@Target({ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
private @interface Async {}

}

Output

2
@java.lang.Deprecated(forRemoval=false, since="")
@com.logicbig.example.method.GetAnnotationsExample$Async()




package com.logicbig.example.method;

import java.lang.annotation.*;
import java.lang.reflect.Method;
import java.util.Arrays;

public class GetAnnotationsExample2 {
private static class Test {
@Deprecated
@Async
public void process() {
}
}

private static class SubTest extends Test {
}

public static void main(String... args) throws NoSuchMethodException {
Method m = SubTest.class.getMethod("process");
Annotation[] annotations = m.getAnnotations();
System.out.println(annotations.length);
Arrays.stream(annotations).forEach(System.out::println);
}

@Inherited
@Target({ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
private @interface Async {}

}

Output

2
@java.lang.Deprecated(forRemoval=false, since="")
@com.logicbig.example.method.GetAnnotationsExample2$Async()




See Also