Forums Register Login

Can Reflection help me ?

+Pie Number of slices to send: Send
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.
+Pie Number of slices to send: Send
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
+Pie Number of slices to send: Send
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.
It's never done THAT before. Explain it to me tiny ad:
a bit of art, as a gift, that will fit in a stocking
https://gardener-gift.com


reply
reply
This thread has been viewed 563 times.
Similar Threads
anonymous classes
max coords
Overloading question
array variables out of scope-why?
IBM question - Interface
More...

All times above are in ranch (not your local) time.
The current ranch time is
Mar 28, 2024 20:34:00.