33

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 ?

Darek
  • 2,861
  • 4
  • 29
  • 52

2 Answers2

44

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;
JNYRanger
  • 6,829
  • 12
  • 53
  • 81
harsh
  • 7,502
  • 3
  • 31
  • 32
  • 3
    Ok so the first example is ok but there is `.value()` not `.value`. The second one does not work since Annotation class does not have a `value()` method. – Darek Nov 25 '13 at 14:55
  • 2
    the second one works but as @Vash showed: MethodSignature ms = (MethodSignature) pjp.getSignature(); Method m = ms.getMethod(); Produces pro = m.getAnnotation(Produces.class); – Darek Nov 25 '13 at 15:05
  • how can i get @Annotation(param1="One", param2="THIS") ? – Ninja Coding Oct 20 '16 at 16:46
  • @NinjaCoding Lets say you used annotation is on a method, once you hold the method object, you can use method.getAnnotation(Annotation.class).param1() to get the param1 value. Here you have named your annotation interface as Annotation. – Dhanaraj Durairaj Mar 26 '17 at 05:03
6

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.