Close

Java Reflection - Method.getAnnotation() 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 <T extends Annotation> T getAnnotation(Class<T> annotationClass)

Returns this element's annotation for the specified type if such an annotation is present, else null.


Examples


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;

public class GetAnnotationExample {

@Async
public void process() {}

public static void main(String... args) throws NoSuchMethodException {
Method m = GetAnnotationExample.class.getDeclaredMethod("process");
Async annotation = m.getAnnotation(Async.class);
System.out.println(annotation);
}

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

Output

@com.logicbig.example.method.GetAnnotationExample$Async()




See Also