在 Java 中获取注解的参数值

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/20192552/
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-13 00:01:24  来源:igfitidea点击:

Get value of a parameter of an annotation in Java

javareflectionaspectj

提问by Darek

So I've got a code:

所以我有一个代码:

@Path("/foo")
public class Hello {

@GET
@Produces("text/html")
public String getHtml(@Context Request request, @Context HttpServletRequest requestss){
  ...
}

I am using AspectJ to catch all calls to getHtmlmethod. I would like to get parameters passed to @Producesand to @Pathin my advice, i.e. "/foo"and "text/html"in this case. How can I do it using reflection ?

我正在使用 AspectJ 来捕获对getHtml方法的所有调用。我想获得传递的参数@Produces,并@Path在我的建议,即"/foo""text/html"在这种情况下。我如何使用反射来做到这一点?

采纳答案by harsh

To get value of the @Pathparameter:

获取@Path参数值:

String path = Hello.class.getAnnotation(Path.class).value();

Similarly, Once you have hold of MethodgetHtml

同样,一旦你掌握了 MethodgetHtml

Method m = Hello.class.getMethod("getHtml", ..);
String mime = m.getAnnotation(Produces.class).value;

回答by Damian Leszczyński - Vash

The annotation is based on interface logic. You need to call the valid member of it to retrieve the value.

注解是基于接口逻辑的。您需要调用它的有效成员来检索该值。

Definition

定义

public @interface Produces {
 String type();
}

Read example

阅读示例

for (Method m: SomeClass.class.getMethods() {
   Produces produce = m.getAnnotation(Produces.class);
   if (produce != null)
       System.out.println(produce.type());
}

Yes. You must use reflection to access to method definition. You can use Class#MgetMethods()to get the definition of method

是的。您必须使用反射来访问方法定义。您可以使用Class#MgetMethods()来获取方法的定义

For object you call obj.getClass()to get the class definition.

对于对象,您调用obj.getClass()以获取类定义。