• Post Reply Bookmark Topic Watch Topic
  • New Topic

Can Reflection help me ?  RSS feed

 
shomps shimps
Greenhorn
Posts: 2
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi,
We have three classes A,B & C. Instance methods of all these classes can
call a method in a Class X.
Now if I want to find out which one out of A,B or C called X then in X's method I can do - this.getClass().getName();
But suppose if X calls another method in class Y and in Y I want to find out whether A called X which in turn called Y or B called X which in turn called Y ...and so on ... then how to do this ?
Please help me.
Thanks in advance.
 
karl koch
Ranch Hand
Posts: 388
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
hi
???
can you give some code ?
i dont think there is a way to find out who called a method (unless you pass the calling object as an argument of the method).

will always return the name of the class that is referenced by this. not the caller class.
probably i got you wrong....can you give some code and tell us why you need to know who called the method.
k
 
Gopi Balaji
Ranch Hand
Posts: 84
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Easy way - change the signature of the method X to pass in a reference of the caller.
Convoluted way - Redirect your System.err to an in-memory buffer. use Thread.dumpStack() to dump the stack. Parse through it to find the class which called method X.
Another Convoluted way - Throw an exception in method X. Capture the stack trace (Throwable.getStackTrace()) and look at its StackTraceElement to see who is the execution stack.
Elegant way - Use AspectJ. Capture the joinpoint of the call of method X, exposing a reference to the caller.
-GB.
 
With a little knowledge, a cast iron skillet is non-stick and lasts a lifetime.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!