2015-07-19 49 views
-1

当我调用类中的方法时,该方法将使用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(); 
    } 
} 

,然后程序会打印出 “酒吧”。

+0

这个不清楚。你是说你想要检索实际的调用**实例**,而不仅仅是类? –

+0

没有一个很好的方法来做到这一点。它*是*可能的,但它也经常是非常糟糕的设计!我唯一见过使用这种方法是日志记录,记录器应该自动处理它...你可以使用Thread.currentThread()。getStackTrace()来获取这些信息。 – Daniel

+0

你为什么要这样做?听起来像一个[XY问题](http://meta.stackexchange.com/questions/66377/what-is-the-xy-problem) –

回答

1

这里是你如何能得到呼叫类快速演示 - 除非你将它传递给方法,因为它不是在栈上,你不能获得主叫对象

public class ReflectDemo { 
    public static class Foo { 
     public static void printOutCallerObject() { 
      StackTraceElement[] trace = Thread.currentThread().getStackTrace(); 
      // trace[0] is Thread.getStackTrace() 
      // trace[1] is Foo.printOutCallerObject() 
      // trace[2] is the caller of printOutCallerObject() 
      System.out.println(trace[2].getClassName()); 
     } 
    } 

    public static class Bar { 
     public static void barMain() { 
      Foo.printOutCallerObject(); 
     } 
    } 

    public static void main(String[] args) { 
     Foo.printOutCallerObject(); 
     Bar.barMain(); 
    } 
} 

此打印:

ReflectDemo 
ReflectDemo$Bar 

而且Foo.printOutCallerObject();会打印出任何的代码调用它的类。致Thread.currentThread().getStackTrace()的电话并不便宜,因此请注意您可能会产生一些运行时成本。这种模式通常用于日志记录,以记录哪一段代码触发了日志记录调用。

+0

这不是我所需要的 - 我需要跟踪返回一个“酒吧”对象。不是类对象。 –

+0

@LucasBaizer就像我说的那样,这是不可能的。调用对象在堆栈上不可用。解决方法是将'this'作为参数传递给'printOutCallerObject()'。 – dimo414