Reputation: 22606
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
}
Upvotes: 50
Views: 68472
Reputation: 296
To get the current method, try using this code:
Thread.currentThread().getStackTrace()[1].getClassName().toString()+\".\"+Thread.currentThread().getStackTrace()[1].getMethodName().toString()
Upvotes: 2
Reputation: 27234
@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()]
Upvotes: 1
Reputation: 100686
Method
instance.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)
Upvotes: 64
Reputation: 14232
Two important things:
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());
}
Upvotes: 25