当我调用类中的方法时,该方法将使用sun.reflect.Reflection.getCallerClass(2)
获取调用它的java.lang.Class
。这不是我想要的。我要反思返回Object类调用它(即,如果我把从Bar
类中的方法,该Reflection.getCallerClass()
返回Bar
类型的对象)从反射中获取类的类型Java
让我们假设我有这个类:
public class Foo {
public static void printOutCallerObject() {
System.out.println(classTypeThatCalledOnMethod);
}
}
调用方式:
public class Bar {
public static void main(String[] args) {
Foo.printOutCallerObject();
}
}
,然后程序会打印出 “酒吧”。
这个不清楚。你是说你想要检索实际的调用**实例**,而不仅仅是类? –
没有一个很好的方法来做到这一点。它*是*可能的,但它也经常是非常糟糕的设计!我唯一见过使用这种方法是日志记录,记录器应该自动处理它...你可以使用Thread.currentThread()。getStackTrace()来获取这些信息。 – Daniel
你为什么要这样做?听起来像一个[XY问题](http://meta.stackexchange.com/questions/66377/what-is-the-xy-problem) –