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

FranAguiar :

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.

Zabuza :

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).

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=111764&siteId=1