在 Java 中查找方法(反射)的调用者
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/21649585/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Find the caller of a method (reflection) in Java
提问by federem
I want to recover in Java the instance of the caller. Here is my code
我想在 Java 中恢复调用者的实例。这是我的代码
class A {
void methodA() {
B b = new B();
A a = b.methodB(); //needs to be the same instance ie "this"
}
}
class B {
A methodB() {
//Here the code (with reflection) I need
A a = getPreviousInstanceCaller();
return A
}
}
Does it exist in Java a way to do that ? Maybe with reflection ?
Java 中是否存在一种方法来做到这一点?也许有反思?
回答by peter.petrov
You don't need reflection for this. You need one of these methods.
你不需要为此反思。您需要其中一种方法。
http://docs.oracle.com/javase/7/docs/api/java/lang/Throwable.html#getStackTrace%28%29
http://docs.oracle.com/javase/7/docs/api/java/lang/Throwable.html#getStackTrace%28%29
http://docs.oracle.com/javase/7/docs/api/java/lang/Thread.html#getStackTrace%28%29
http://docs.oracle.com/javase/7/docs/api/java/lang/Thread.html#getStackTrace%28%29
Note that the ordering of the stack trace elements (0, 1, 2, etc.)
may vary in different versions of the JDK. Meaning in some versions
element 0 may be the top-most element, while in others it may be the
bottom-most one. This is an important thing to have in mind.
请注意,堆栈跟踪元素(0、1、2 等)的顺序
在 JDK 的不同版本中可能会有所不同。这意味着在某些版本中
元素 0 可能是最顶部的元素,而在其他版本中它可能是
最底部的元素。这是一件很重要的事情。
See here for more details.
请参阅此处了解更多详情。