首页 > 解决方案 > How can I get the caller class object from a method in java?

问题描述

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.

标签: javaclass

解决方案


如果您使用的是 Java 9+,则可以使用java.lang.StackWalker.

public void foo() {
    Class<?> caller = StackWalker.getInstance(Option.RETAIN_CLASS_REFERENCE)
            .getCallerClass();
}

但是,由于StackWalker是线程安全的,因此创建一个实例并将其存储在某处可能是有益的(而不是每次调用该方法时都创建一个新实例)。

的Javadoc getCallerClass()

获取Class调用方法的调用者的对象getCallerClass

此方法过滤反射帧、MethodHandle和隐藏帧,而不管已配置的SHOW_REFLECT_FRAMESSHOW_HIDDEN_FRAMES选项。StackWalker

当调用者框架存在时,应该调用此方法。如果从堆栈的最底部帧调用它,IllegalCallerException 将被抛出。

UnsupportedOperationException如果StackWalker 未使用该RETAIN_CLASS_REFERENCE选项配置此方法,则会引发此方法。


推荐阅读