Reputation: 647
I know I can get the method and classname from StackTraceElement[] stackTrace = Thread.currentThread().getStackTrace();
but that is not what I want.
I want the class object, so I can access his interface, annotations, etc...
It is possible?
Class<?> classObject = getCallerClass();
I see this question, but that is just for the classname.
How to get the caller class in Java
Edit: Now I'm passing the class this way:
someService.dummyMethod(foo1, foo2, new Object(){}.getClass());
someService(String foo1, int foo2, Class<?> c) {
// stuff here to get the methodname,
// the interface of the class and an annotation from the interface.
}
I call someService from a lot of different classes, If is not possible I will continue this way, but If there is a way to get the caller class at runtime I prefer that way.
Upvotes: 4
Views: 8269
Reputation: 45806
If you're using Java 9+ you can use java.lang.StackWalker
.
public void foo() {
Class<?> caller = StackWalker.getInstance(Option.RETAIN_CLASS_REFERENCE)
.getCallerClass();
}
However, since StackWalker
is thread safe it might be beneficial to create an instance and store it somewhere (rather than create a new instance every time the method is called).
Javadoc of getCallerClass()
:
Gets the
Class
object of the caller who invoked the method that invokedgetCallerClass
.This method filters reflection frames,
MethodHandle
, and hidden frames regardless of theSHOW_REFLECT_FRAMES
andSHOW_HIDDEN_FRAMES
options thisStackWalker
has been configured with.This method should be called when a caller frame is present. If it is called from the bottom most frame on the stack,
IllegalCallerException
will be thrown.This method throws
UnsupportedOperationException
if thisStackWalker
is not configured with theRETAIN_CLASS_REFERENCE
option.
Upvotes: 7
Reputation: 25903
Get the classname using the code of your linked question: How to get the caller class in Java
Then use the classname to retrieve the class, using code from here: Getting class by its name
Complete code:
String callerName = Thread.currentThread().getStackTrace()[2].getClassName();
try {
Class<?> caller = Class.forName(callerName);
// Do something with it ...
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
(community answer, since only mix of existing answers).
Upvotes: 6