Java中如何使用反射获取注解的值

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/18340666/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-12 00:42:22  来源:igfitidea点击:

How to get the value of annotation using Reflection in Java

javareflectionannotations

提问by Mythul

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

如何使用 Java 获取注释的值Reflection

This is the annotated method:

这是带注释的方法:

@JsonView( { View.class } )
public Element getElement()
{
    return element;
}

采纳答案by Selvaraj

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

回答by AlexR

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

假设您的方法是在 class 中声明的MyClass,请执行以下操作:

MyClass.class.getMethod("getElement").getAnnotation(JsonView.class).value()