Wednesday, October 15, 2014

How to find which method called the current method at runtime


I’m using the following helper class to find which method called the current method (at runtime.)

import java.lang.reflect.Method;
import java.security.AccessController;
import java.security.PrivilegedAction;

public class TraceHelper {
    private volatile static Method m;
    private static Throwable t;

    public TraceHelper() {
        try {
            m = Throwable.class.getDeclaredMethod("getStackTraceElement", int.class);
            AccessController.doPrivileged(
                    new PrivilegedAction() {
                        public Object run() {
                            m.setAccessible(true);
                            return null;
                        }
                    }
            );
            t = new Throwable();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public String getMethodName(final int depth, boolean useNew) {
        return getMethod(depth, t != null && !useNew ? t : new Throwable());
    }

    public String getMethod(final int depth, Throwable t) {
        try {
            StackTraceElement element = (StackTraceElement) m.invoke(t, depth + 1);
            return element.getClassName() + "$" + element.getMethodName();
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

}
Then I use the following code inside my aspect to get the name of the method which called my current (executing) method.
String previousMethodName = new TraceHelper().getMethodName(2, false);

No comments: