How to get the value of annotation using Reflectio

2020-04-08 12:10发布

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;
}

2条回答
干净又极端
2楼-- · 2020-04-08 12:58

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
查看更多
一纸荒年 Trace。
3楼-- · 2020-04-08 13:10

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

MyClass.class.getMethod("getElement").getAnnotation(JsonView.class).value()
查看更多
登录 后发表回答