Example of how to write functions that return the name of the calling method (only works in Java 1.5):
public static String getCallingMethod() { return trace(Thread.currentThread().getStackTrace(), 2); } public static String getCallingMethod(int level) { return trace(Thread.currentThread().getStackTrace(), 2 + level); } private static String trace(StackTraceElement e[], int level) { if(e != null && e.length >= level) { StackTraceElement s = e[level]; if(s != null) { return s.getMethodName(); } } return null; }
JUnit test for this (assuming the methods above were written in a class called StackUtil):
public class StackUtilTests extends TestCase { public void testGetCallingMethod() { String callingMethod = StackUtil.getCallingMethod(); System.out.println("callingMethod = " + callingMethod); assertEquals("testGetCallingMethod", callingMethod); } public void testGetCallingMethodWithLevel() { String callingMethod = StackUtil.getCallingMethod(0); System.out.println("callingMethod = " + callingMethod); assertEquals("testGetCallingMethodWithLevel", callingMethod); } public void testGetCallingMethodOneLevel() { String callingMethod = testGetCallingMethodOneLevelPrivate(); assertEquals("testGetCallingMethodOneLevel", callingMethod); } private String testGetCallingMethodOneLevelPrivate() { String callingMethod = StackUtil.getCallingMethod(1); System.out.println("callingMethod = " + callingMethod); return callingMethod; } }
© 2017 Nilesh D Kapadia