aps
aps

Reputation: 2472

Getting a reference to the object which is trying to create me

Let's say there is a class called Node and another class called Table. A node object can create a Table object. Obviously then the Table class' constructor is called. Is it possible to get from within the Table constructor, a reference to the Node object which is creating this Table instance? One way is if while creating the object, I force the Node object to pass "this" as a parameter to the Table constructor. Is there any other way where no parameter needs to be passed?

Upvotes: 2

Views: 92

Answers (3)

maerics
maerics

Reputation: 156534

The only way to get a reference to the "calling" object (the instance calling a method, constructor, etc.) in the Java language is to pass the "this" object reference to the "receiver" method which needs to know. There is no other way using plain Java, AFAIK.

Upvotes: 1

gtiwari333
gtiwari333

Reputation: 25156

Here is a complete Example

public class GivesNameOfCallingClass {
//constructor
    public GivesNameOfCallingClass() {
        try {
            throw new Exception("Error");
        }
        catch (Exception e) {
            System.out.println(e.getStackTrace()[1].getClassName());
        }
    }
}

And Test Class

public class GetNameOfCallingClassTest {
    public static void main(String[] args) {
        new GivesNameOfCallingClass();
    }
}

Upvotes: 0

OsQu
OsQu

Reputation: 1058

I believe you can use Thread.getCurrentThread.getStackTrace() to access to the call stack and find out the class name that called it. e.g.

Thread.getCurrentThread().getStackTrace()[1].getClassName();

But if you want to access the instance of that object then I think the only way to access it is to pass 'this' to the constructor.

Upvotes: 2

Related Questions