[英]How can I find the class/package/instance that creates object of my class?
I am implementing a class that is supposed to have a instance in many different parts of a bigger project. 我正在实现一个类,该类应该在较大项目的许多不同部分中都有一个实例。 How can I find out at runtime where an object of my class was created?
如何在运行时查找创建类对象的位置? For example in which class or in which package.
例如在哪个类或哪个包中。
Retrieve the stack of the call than access the single StackTraceElement as needed: 检索调用的堆栈,然后根据需要访问单个StackTraceElement:
public YourConstructor() {
....
StackTraceElement[] stackTraceElements = Thread.currentThread().getStackTrace();
int depth = 1; // Check for different depths is necessary.
System.out.println(stackTraceElements[depth].getClassName());
...
}
Well you can use Java's stacktrace element. 好了,您可以使用Java的stacktrace元素。
Check here for that and more alternatives How do I find the caller of a method using stacktrace or reflection? 在此处检查更多替代方案如何使用stacktrace或反射找到方法的调用方?
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.