• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Is there any way an initialized instance knows who initialized it without passing information to it?

 
Kjeld Sigtermans
Ranch Hand
Posts: 127
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi,

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.

Thanks!
Kjeld

 
Maneesh Godbole
Saloon Keeper
Posts: 11064
13
Android Eclipse IDE Google Web Toolkit Java Mac Ubuntu
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I don't think so.
Usually, in such scenarios, you pass a reference of Test to Foo.

 
Henry Wong
author
Marshal
Pie
Posts: 21190
80
C++ Chrome Eclipse IDE Firefox Browser Java jQuery Linux VI Editor Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

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.

Henry
 
Maneesh Godbole
Saloon Keeper
Posts: 11064
13
Android Eclipse IDE Google Web Toolkit Java Mac Ubuntu
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Henry!
You think of everything! This is a very interesting usage of Exceptions. I must remember this.
Thank you.
 
Jesper de Jong
Java Cowboy
Saloon Keeper
Posts: 15354
39
Android IntelliJ IDE Java Scala Spring
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.).
 
Kjeld Sigtermans
Ranch Hand
Posts: 127
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.

 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic