This week's book giveaway is in the OO, Patterns, UML and Refactoring forum. We're giving away four copies of Refactoring for Software Design Smells: Managing Technical Debt and have Girish Suryanarayana, Ganesh Samarthyam & Tushar Sharma on-line! See this thread for details.
Consider a class Test. In the constructor of Test (or a method of Test) a class Foo is declared and initialized.
Question: is it possible that Foo knows who initialized it? That is, without sending an instance of Test to the constructor of Foo.
Interestingly, this *is* possible. It is just not guaranteed to work.
In the Foo constructor, create an Exception --> get the stack trace elements. For each stack trace element, get the class name --> get the class object via class.forName(). The first stack trace element class that is not the Foo class object, should be the class that initialized.
Of course, on some JVMs, it is possible to turn off stack tracing, so this may not work.
That's a clever trick, but I would never use something like that in a real application.
Kjeld, why does your class Foo need to know this? When you encounter unusual requirements like this while writing a program, it's usually a sign that there's a problem with the design of your program. Can't you solve whatever the problem is with OO techniques? (Polymorphism, etc.).
Well it's just something I wanted to know. We're using Log4J logging in our project and for several reasons we'd like to create our own Logger class, encapsulating the Log4J functionality. What I'd like to do, is to instantiate our own Logger class without having to tell it who instantiated it. But perhaps I could pass it a 'this' reference and use the getClass() method.
Love the Exception solution LOL but of course that's a very very 'dirty' solution.
I’ve looked at a lot of different solutions, and in my humble opinion Aspose is the way to go. Here’s the link: http://aspose.com
subject: Is there any way an initialized instance knows who initialized it without passing information to it?