简体   繁体   English

如何找到创建类对象的类/包/实例?

[英]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.

相关问题 如果实例方法创建内部类,如何让其修改对象? - How to have an instance method modify object if it creates inner class? 如何将文件名字符串传递给另一个 Class 以便它在该 class 中创建文件 object? - How can I pass a filename String to another Class so that it creates a File object in that class? 如何控制 JUnit 是否创建正在测试其行为的类的实例? - How can I control whether JUnit creates an instance of the class whose behaviour is being tested? 如何获取在类中确定的对象的实例 - How can I get the instance of an object that is determined in the class 如何在`main()`中创建我的Iterator私有类的实例 - How can I create an instance of my Iterator private class in `main()` 我可以覆盖类对象的新实例吗? - Can I override a new instance of a class object? 如何在Java中在运行时找到类的实例? - How can find an instance of class at runtime in Java? 如果将类用作类型参数,如何在参数化的类中创建此对象的实例? - If I use a class as a type parameter, how can I create an instance of this object within the parameterized class? 给定类成员名称或对象,如何在Java中找到其声明/封闭类对象? - Given a class member name or object, how can I find its declaring/enclosing class object in java? 我如何从AsyncTask中的数据库类中获取对象? - How i can get object from my database class in AsyncTask?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM