Get value of a parameter of an annotation in Java

前端 未结 2 1378
梦谈多话
梦谈多话 2020-12-06 09:19

So I\'ve got a code:

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

@GET
@Produces(\"text/html\")
public String getHtml(@Context Request request, @Context HttpServlet         


        
相关标签:
2条回答
  • 2020-12-06 09:35

    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;
    
    0 讨论(0)
  • 2020-12-06 09:49

    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.

    0 讨论(0)
提交回复
热议问题