Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I get the caller class object from a method in java?

Tags:

java

class

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.

like image 222
FranAguiar Avatar asked Oct 25 '25 00:10

FranAguiar


1 Answers

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 invoked getCallerClass.

This method filters reflection frames, MethodHandle, and hidden frames regardless of the SHOW_REFLECT_FRAMES and SHOW_HIDDEN_FRAMES options this StackWalker 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 this StackWalker is not configured with the RETAIN_CLASS_REFERENCE option.

like image 198
Slaw Avatar answered Oct 26 '25 14:10

Slaw