2

Just wondering, how do you find out the name of the method that invokes another method? I want to use the Method class.

FlameKnight123
  • 39
  • 1
  • 1
  • 4

2 Answers2

6

You can make use of StackTraceElement :

StackTraceElement[] stackTraceElements = Thread.currentThread().getStackTrace();

Order of elements in StackTraceElement array: The last element of the array represents the bottom of the stack, which is the least recent method invocation in the sequence.

Once you have the desired method name then you can call it using reflection :

Method lastMethod = YourClass.class.getMethod("yourMethodName");
lastMethod.invoke();

Note: The code should be changed as per your class and method.

Juned Ahsan
  • 67,789
  • 12
  • 98
  • 136
0

Getting the name is tricky enough, getting the method is very hard because you don't know the argument list but you do know the class and you can use the line number when reading the byte code to find which method which contains that line. If the method is static (and I suspect its not) you are ok. If you need an instance, finding that is next to impossible in any portable way.

The sort of thing you are trying to do is the Java equivalent of saying; how do I learn to flight in a couple of easy steps.

What ever your problem is this is highly unlikely to be a good solution. If you need to call back to the object which called you, you should pass that object as an argument, ideally via an interface.

When ever you find the code running back on itself, this is sure to end in a mess of some kind, You want to simplify your dependencies.

What you should do is something like this.

interface Callback<T> {
    onResult(T t);
}


class A implements Callback<MyResult> {
    B b = new B();
    public void method() {
        b.doSomething(this);
    }
    public void onResult(MyResult mr) {
        // do something with mr
    }
}

class B {
    public void doSomething(Callback<MyResult> cb) {
         // do something
         cb.onResult(new MyResult(something));
         // do something else
    }
}

Of course this would be all much simpler if instead of call back on the first method, you just returned a result and half this code wouldn't be needed. This is why normally when you want to pass something back to the caller, you use a return value instead of recursion.

Peter Lawrey
  • 525,659
  • 79
  • 751
  • 1,130