Retrieve Java Annotation Attribute
- Obtain
Method
instance. - Obtain annotation.
- 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)
Two important things:
- There is no way to get the current method, e.g. there is no getMethod() such as getClass(). Therefore, the method accessing its own annotation would need to know its own name.
- The retention policy of the annotation must be set to
RUNTIME
, so you can access the annotation at runtime. The default is compile-time, which means annotations are available in the class file, but cannot be accessed at runtime using reflection.
Full example:
@Retention(RetentionPolicy.RUNTIME)
public static @interface MyAnnotation {
String value1();
int value2();
}
@Test
@MyAnnotation(value1 = "Foo", value2 = 1337)
public void testAnnotation() throws Exception {
Method[] methods = getClass().getMethods();
Method method = methods[0];
assertEquals("testAnnotation", method.getName());
MyAnnotation annotation = method.getAnnotation(MyAnnotation.class);
assertEquals("Foo", annotation.value1());
assertEquals(1337, annotation.value2());
}
To get the current method, try using this code:
Thread.currentThread().getStackTrace()[1].getClassName().toString()+\".\"+Thread.currentThread().getStackTrace()[1].getMethodName().toString()
@mhaller: a bit too long for a comment on your post. Obviously would need further refinement to deal with overloaded methods, but it is not impossible.:
import java.lang.reflect.Method;
public class Hack {
public static void main (String[] args) {
(new Hack()).foobar();
}
public void foobar () {
Method here = getCurrentMethod(this);
System.out.format("And here we are: %s\n", here);
}
public static final Method getCurrentMethod(Object o) {
String s = Thread.currentThread().getStackTrace()[2].getMethodName();
Method cm = null;
for(Method m : o.getClass().getMethods()){
if(m.getName().equals(s)){
cm = m; break;
}
}
return cm;
}
}
[edit: credit/thanks to Alexandr Priymak for spotting the error in main()]