<<
Class Method Reflector
The below code returns the current method name (i.e. the name of the method which is currently executing), the calling method name, and the calling Class name. These could be useful for debugging purposes.
Note, they only work in Java 5+, but could be modifed to work in Java 1.4 by using (new Exception().getStackTrace()[0].getMethodName());
1:
2:
3:
4:
5:
6:
7:
8:
9:
10:
11:
12:
13:
14:
15:
16:
17:
18:
19:
20:
21:
22:
23:
24:
25:
26:
27:
28:
29:
30:
31:
32:
33:
34:
35:
36:
37:
38:
39:
40:
41:
42:
43:
44:
45:
46:
47:
48:
49:
50:
51:
52:
53:
54:
public class ClassMethodReflector {
public static String getCurrentMethodName() {
StackTraceElement st;
if ( ( st = getStackTraceElement(0) ) != null ) {
return st.getMethodName();
}
return null;
}
public static String getCallingMethodName() {
StackTraceElement st;
if ( ( st = getStackTraceElement(1) ) != null ) {
return st.getMethodName();
}
return null;
}
public static String getCallingClassName() {
StackTraceElement st;
if ( ( st = getStackTraceElement(1) ) != null ) {
return st.getClassName();
}
return null;
}
public static String getCallingClassSimpleName() {
StackTraceElement st;
if ( ( st = getStackTraceElement(1) ) != null ) {
String c = st.getClassName();
return c.substring( c.lastIndexOf( "." ) + 1 );
}
return null;
}
private static StackTraceElement getStackTraceElement( int _offset ) {
StackTraceElement[] stackTrace = Thread.currentThread().getStackTrace();
int i = 0;
String methodName;
do {
methodName = stackTrace[i++].getMethodName();
} while ( ! methodName.equals( "getStackTrace" ) );
if ( (i = i + 2 + _offset ) <= stackTrace.length - 1 ) {
return stackTrace[i];
}
return null;
}
}