简体   繁体   English

获取Java中注释参数的值

[英]Get value of a parameter of an annotation in Java

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 getHtml method. 我使用AspectJ来捕获所有对getHtml方法的调用。 I would like to get parameters passed to @Produces and to @Path in my advice, ie "/foo" and "text/html" in this case. 我想在我的建议中将参数传递给@Produces@Path ,在这种情况下是"/foo""text/html" How can I do it using reflection ? 我怎么能用反射来做呢?

To get value of the @Path parameter: 要获取@Path参数的值:

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

Similarly, Once you have hold of Method getHtml 同样,一旦掌握了Method getHtml

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

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()来获取类定义。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM