Reputation: 529
I want to get a value in annotation from method that is calling another method and that needs to be used with annotation used in called method.
Example
@MyAnnotation(id="method-invoker")
public void invoker(){
executor();
}
@ChildMethod
public void executor(){
}
In above example I want to get value set in id
field in @MyAnnotation
when handling @ChildMethod
annotation.
How can I do this?
Upvotes: 1
Views: 1518
Reputation: 115328
First you have to get the stack trace, then extract caller's name from it, then get the Method
and get its annotation:
String id = getClass().getMethod(new Throwable().getStackTrace()[1].getMethodName()).getAnnotation(MyAnnotation.class).id();
(obviously it is a bad style to perform so many calls sequentially in one line, but it is ok for example).
But this method is limited. It does not support methods overloading. For example if you have 2 methods called invoker()
that have different signature in one class you cannot distinguish between them using pure reflection API.
Fortunately I implemented library named CallStack that can do this: https://github.com/alexradzin/callstack
Using CallStack
you can say:
CallStack.getCallStack().getFunction().getAnnotation(MyAnnotation.class).id()
Upvotes: 4