Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get the value of annotation using Reflection in Java [closed]

How can I get the value of the annotation using Java Reflection ?

This is the annotated method:

@JsonView( { View.class } )
public Element getElement()
{
    return element;
}
like image 441
Mythul Avatar asked Dec 20 '22 01:12

Mythul


2 Answers

Assuming that your method is declared in class MyClass, do the following:

MyClass.class.getMethod("getElement").getAnnotation(JsonView.class).value()
like image 130
AlexR Avatar answered Jan 13 '23 13:01

AlexR


Here the some way to get annotation,

Class<?> cls = Class.forName(name);

    cls.getDeclaredAnnotations(); // get all annotation
    (cls.getDeclaredMethods()[0]).getAnnotations(); //get annotation of a method
    Annotation ety = cls.getAnnotation(Annotation.class); // get annotation of particular annotation class
like image 24
Selvaraj Avatar answered Jan 13 '23 15:01

Selvaraj