This week's book giveaways are in the Refactoring and Agile forums.
We're giving away four copies each of Re-engineering Legacy Software and Docker in Action and have the authors on-line!
See this thread and this one for details.
Win a copy of Re-engineering Legacy Software this week in the Refactoring forum
or Docker in Action in the Cloud/Virtualization forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Who called?

 
Michael Labuschagne
Ranch Hand
Posts: 56
Java Tomcat Server Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
If you have two classes (Class A and Class B) with Class A having method A and class B having method B. If in method A you invoke method B is there a way that method B can find out the class which invoked the call?

i.e. how can the callee find out who the caller is without passing an extra parameters (this) from within the caller.
 
Peter Chase
Ranch Hand
Posts: 1970
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You can find where you were called from by examining the stack. Use Thread.getStackTrace().
 
Michael Labuschagne
Ranch Hand
Posts: 56
Java Tomcat Server Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
OK... lets give the example more perspective.

Class A (has method A) and Class B(had method B)...

in method B you have a JButton which is passed to method B via the a call from method A. Within method B i want to addActionListener(instance of the calling class)

How do you get reference to the particular instance of the calling class? Thereby leaving the implementation of actionPerformed method to the bounds of Class A?
 
Peter Chase
Ranch Hand
Posts: 1970
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You can't do that. You'll need to pass "this".
 
Bupjae Lee
Ranch Hand
Posts: 107
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
When you use ActionListener.actionPerformed(ActionEvent event), you can call event.getSource() and determine which object did generate that event.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic