How to check if a parameter of the current method has an annotation and retrieve that parameter value in Java?

前端 未结 3 1996
逝去的感伤
逝去的感伤 2021-02-08 06:50

Consider this code:

public example(String s, int i, @Foo Bar bar) {
  /* ... */
}

I want to check if the method has an annotation @Foo

3条回答
  •  死守一世寂寞
    2021-02-08 07:06

    If you're looking for annotations on the method, you probably want method.getAnnotations() or method.getDeclaredAnnotations().

    The method.getParameterAnnotations() call gives you annotations on the method's formal parameters, not on the method itself.

    Looking back at the question title, I suspect you are looking for annotations on the parameters, which I didn't read in the content of the question. If that's the case, your code looks fine.

    See Method Javadoc and AnnotatedElement Javadoc.

提交回复
热议问题