This week's giveaway is in the EJB and other Java EE Technologies forum. We're giving away four copies of EJB 3 in Action and have Debu Panda, Reza Rahman, Ryan Cuprak, and Michael Remijan 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.