Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Retrieve Java Annotation Attribute

How can I retrieve the value of an annotation on the annotated method??

I have:

@myAnnotation(attribute1 = value1, attibute2 = value2) public void myMethod() {   //I want to get value1 here } 
like image 376
Diego Dias Avatar asked Nov 26 '09 19:11

Diego Dias


People also ask

How do you get annotations?

getAnnotation(Class< T > annotationClass) method of Method class returns Method objects's annotation for the specified type passed as parameter if such an annotation is present, else null. This is important method to get annotation for Method object.

How do you inherit annotations?

Annotations, just like methods or fields, can be inherited between class hierarchies. If an annotation declaration is marked with @Inherited , then a class that extends another class with this annotation can inherit it. The annotation can be overridden in case the child class has the annotation.

How do you find a class annotation?

The getAnnotation() method of java. lang. Class class is used to get the annotation of the specified annotation type, if such an annotation is present in this class. The method returns that class in the form of an object.

What is @interface annotation in Java?

Annotation is defined like a ordinary Java interface, but with an '@' preceding the interface keyword (i.e., @interface ). You can declare methods inside an annotation definition (just like declaring abstract method inside an interface). These methods are called elements instead.


1 Answers

  1. Obtain Method instance.
  2. Obtain annotation.
  3. Obtain annotation attribute value.

Something like:

Method m = getClass().getMethod("myMethod"); MyAnnotation a = m.getAnnotation(MyAnnotation.class); MyValueType value1 = a.attribute1(); 

You'll need to catch / handle the appropriate exceptions, of course. The above assumes you are indeed retrieving method from the current class (replace getClass() with Class.forName() otherwise) and the method in question is public (use getDeclaredMethods() if that's not the case)

like image 77
ChssPly76 Avatar answered Sep 19 '22 17:09

ChssPly76