Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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. 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 ?

like image 505
Darek Avatar asked Nov 25 '13 12:11

Darek


People also ask

How to get parameter annotation in Java?

getParameterAnnotations() method of Method class returns a two-dimensional Annotation array, that represents the annotations on the parameters, of the Method object. If the Method contains no parameters, an empty array will be returned.

What is @interface annotation in Java?

@interface is used to create your own (custom) Java annotations. Annotations are defined in their own file, just like a Java class or interface. Here is custom Java annotation example: @interface MyAnnotation { String value(); String name(); int age(); String[] newNames(); }

How do you pass value to custom annotations?

Annotations require constant values and a method parameter is dynamic. Show activity on this post. Annotation Usage: @CacheClear(pathToVersionId = "[0]") public int importByVersionId(Long versionTo){ ...... }

What is retention policy in Java?

Retention Policy: A retention policy determines at what point an annotation is discarded. It is s specified using Java's built-in annotations: @Retention [About] 1. SOURCE: annotation retained only in the source file and is discarded during compilation.


1 Answers

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; 
like image 133
harsh Avatar answered Sep 18 '22 07:09

harsh