views:

128

answers:

3

How can i get hold of the instantiating object from a constructor in java?

I want to store reference to the parent object for some GUI classes to simulate event bubbling - calling parents handlers - but i dont wanna change all the existing code.

+1  A: 

Intercepting method calls (including constructors) without changing a ton of existing code is one thing Aspect-oriented programming was made for.

Check out AspectJ for a start.

With AspectJ, you can define a "pointcut" that specifies that you want to intercept constructor calls for a certain object or set of objects (using wildcards if need be), and within the interception code ("advice"), you will be given method context, which includes information about the both the calling method and object.

You can even use AspectJ to add fields to your object's to store the parent reference without modifying their existing code (this is called "introduction").

JoshJordan
Thanks for the input, but adding more libs to the code base is not something I want to do. I was hoping for a quick and easy solution to the problem using just java.
junior
...it becomes Java! Sorry, couldn't resist. Good luck!
JoshJordan
+5  A: 

Short answer: there isn't a way to do this in Java. (You can find out what class called you, but the long answer below applies there for the most part as well.)

Long answer: Code that magically behaves differently depending on where it's being invoked from is almost always a bad idea. It's confusing to whoever has to maintain your code, and it seriously hurts your ability to refactor. For example, suppose you realize that two of the places instantiating your object have basicaly the same logic, so you decide to factor out the common bits. Surprise! Now the code behaves differently because it's being instantiated from somewhere else. Just add the parameter and fix the callers. It'll save you time in the long run.

Laurence Gonsalves
+3  A: 

If you want to know the invoking class, then pass "this" as a parameter to the constructor.

Thing thing = new Thing(this);


Edit: A modern IDE allowing refactoring will make this very easy to do.

Thorbjørn Ravn Andersen
This also indicates that `Thing` is a candidate for an inner class.
erickson