Get value of a parameter of an annotation in Java

无人久伴 提交于 2019-12-28 16:32:10

问题


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. I would like to get parameters passed to @Produces and to @Path in my advice, i.e. "/foo" and "text/html" in this case. How can I do it using reflection ?


回答1:


To get value of the @Path parameter:

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

Similarly, Once you have hold of Method getHtml

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



回答2:


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

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



来源:https://stackoverflow.com/questions/20192552/get-value-of-a-parameter-of-an-annotation-in-java

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!