Tuesday, August 9, 2011

How to get 'current' method

Hi, I need to get current method in java, one solution is of course using Thread.currentThread().getStackTrace() but its not portable because: Some virtual machines may, under some circumstances, omit one or more stack frames from the stack trace. So I used following solution, not so good but works

    public void testMethod() {

        Method currentMethod = new MethodHelper() {
            @Override
            public Method getCurrentMethod() {
                return getClass().getEnclosingMethod();
            }
        }.getCurrentMethod();
        ...................................
    }
 
    and

    public interface MethodHelper {
        Method getCurrentMethod();
    }

PS: please read getEnclosingMethod() JavaDoc it can return null as well.