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.
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
Classobject of the caller who invoked the method that invokedgetCallerClass.This method filters reflection frames,
MethodHandle, and hidden frames regardless of theSHOW_REFLECT_FRAMESandSHOW_HIDDEN_FRAMESoptions thisStackWalkerhas 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,
IllegalCallerExceptionwill be thrown.This method throws
UnsupportedOperationExceptionif thisStackWalkeris not configured with theRETAIN_CLASS_REFERENCEoption.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With