Close

Java Reflection - Method.getDeclaredAnnotations() 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[] getDeclaredAnnotations()

Returns annotations that are directly present on this method.


Examples


package com.logicbig.example.method;

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

public class GetDeclaredAnnotationsExample {
@Async
public void process(){}

public static void main(String... args) throws NoSuchMethodException {
Method m = GetDeclaredAnnotationsExample.class.getDeclaredMethod("process");
Annotation[] annotations = m.getDeclaredAnnotations();
System.out.println(Arrays.toString(annotations));
}
@Target({ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
private @interface Async {}
}

Output

[@com.logicbig.example.method.GetDeclaredAnnotationsExample$Async()]




package com.logicbig.example.method;

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

public class GetDeclaredAnnotationsExample2 {

public static void main(String... args) throws NoSuchMethodException {
Method m = GetDeclaredAnnotationsExample2.Task.class.getDeclaredMethod("process");
Annotation[] annotations = m.getDeclaredAnnotations();
System.out.println(Arrays.toString(annotations));
}

private static class Processor {
@Async
public void process() {}
}

public static class Task extends Processor {
}

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

Output

[@com.logicbig.example.method.GetDeclaredAnnotationsExample2$Async()]




See Also