How to get annotation value using Reflection in Java

How can I get annotation value using Java Reflection ?

This is the annotated method:

 @JsonView( { View.class } ) public Element getElement() { return element; } 
+4
source share
2 answers

Here is 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 
+4
source

Assuming your method is declared in the MyClass class, follow these steps:

 MyClass.class.getMethod("getElement").getAnnotation(JsonView.class).value() 
+7
source

Source: https://habr.com/ru/post/1498046/


All Articles