Christian
Christian

Reputation: 1411

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.

Upvotes: 1

Views: 54

Answers (2)

Davide Lorenzo MARINO
Davide Lorenzo MARINO

Reputation: 26926

Retrieve the stack of the call than access the single StackTraceElement as needed:

public YourConstructor() {
     ....
     StackTraceElement[] stackTraceElements = Thread.currentThread().getStackTrace();
     int depth = 1;   // Check for different depths is necessary.
     System.out.println(stackTraceElements[depth].getClassName());
     ...
}

Upvotes: 1

saurav
saurav

Reputation: 5926

Well you can use Java's stacktrace element.

Check here for that and more alternatives How do I find the caller of a method using stacktrace or reflection?

Upvotes: 0

Related Questions