1

I was browsing around through the API and tried googling this, but I imagine that I can't word it correctly or its just not possible. My question is: Is it possible to have a method execute a specific sequence of code based on where it was called from?

Slicktopher
  • 137
  • 2
  • 10
  • 5
    Pass in an argument and use if-else. – Sotirios Delimanolis Mar 07 '13 at 14:25
  • 1
    you can execute different code inside a method on different calls independent from where you call the method. – navyad Mar 07 '13 at 14:28
  • 1
    In general a java method should not know or care from where it was called, to do so violates principles of encapsulation and cohesion. This kind of behaviour should be modelled using the Strategy or possibly the Visitor pattern (wikipedia has good descriptions). – sbk Mar 07 '13 at 14:30
  • 1
    Do you want to overload the method perhaps? What are you trying to accomplish? Why would you want to do this? – Jonathan Vance Mar 07 '13 at 14:31
  • What are you trying to do? The simplest solution is to have two method which do different things and the caller calls the right method. – Peter Lawrey Mar 07 '13 at 18:16

3 Answers3

4

You can get the current stacktrace and figure out from that which method called your current method.

This seems incredibly dirty, though, so you should make sure that your use case actually warrants this approach, rather than just adding a parameter to the method or creating different methods.

Community
  • 1
  • 1
Henrik Aasted Sørensen
  • 6,966
  • 11
  • 51
  • 60
3

It looks like a good place for inheritance and two different implementations

ozma
  • 1,633
  • 1
  • 20
  • 28
3

Yes it is possible. But it is probably a bad idea.

One way to achieve this kind of thing goes like this:

public void myMethod(...) {
    Exception ex = new Exception();
    StackTraceElement caller = ex.getStackTrace()[1];
    if (caller.getMethod().equals("someMethod") {
        // do this 
    } else {
        // do that
    }
}

The StackTraceElement gives the name of the method, the name of the declaring class, and when available the name of the source file and the source line number.

There are a couple of reasons why this is a bad idea:

  • This kind of stuff tends to be fragile. It is hard to predict beforehand where a method is going to be called from, and hard to anticipate changes that may be made by another developer sometime in the future.
  • It is expensive to build the stacktrace array, especially if the stack is deep.
  • It violates the "least surprise" rule. Developers don't expect methods to behave like that.
  • There is most likely a better way to do ... whatever it is you are trying to achieve.
Stephen C
  • 698,415
  • 94
  • 811
  • 1,216