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 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111
|
/**
* Class for investigating the call stack.
*
* @author John Evans (john@jpevans.com)
*/
public class Callstack {
/**
* Private Constructor to prevent instantiations.
*/
private Callstack() {
// Do nothing, as we will never be called.
}
/**
* Get the class of the method that called the method that called this
* method.
*
* @return String the name of the class that called the method that called
* this method.
*/
public static String getCallingClass() {
return getCallerInfo(true, false);
}
/**
* Get the method of the method that called the method that called this
* method.
*
* @return String the name of the method that called the method that called
* this method.
*/
public static String getCallingMethod() {
return getCallerInfo(false, true);
}
/**
* Gets 'em both. (See docs for other methods in this class. Should be
* obvious anyway).
*
* @return I don't know why she swallowed the fly.
*/
public static String getCallingClassAndMethod() {
return getCallerInfo(true, true);
}
/**
* The method that does the heavy lifting for the other public methods of
* this class.
*
* @param includeClass
* Should the class be included?
* @param includeMethod
* Should the method be included?
* @return The class and/or method of the method that called into the
* Callstack class.
*/
public static String getCallerInfo(boolean includeClass,
boolean includeMethod) {
StringBuffer result = null;
if (includeClass || includeMethod) {
Exception utilException = new Exception();
StackTraceElement[] stackElements = utilException.getStackTrace();
int i = findFirstNotOneOfUs(stackElements) + 1;
if ((-1 != i) && (i < stackElements.length)) {
StackTraceElement theOneWeWant = stackElements[i];
if (includeClass) {
result = new StringBuffer(theOneWeWant.getClassName());
}
if (includeMethod) {
if (result == null) {
result = new StringBuffer();
} else {
result.append(".");
}
result.append(theOneWeWant.getMethodName());
}
}
}
return (result == null) ? null : result.toString();
}
/**
* Find the first caller outside of the methods within Callstack.
*
* @param elements
* The stack to search.
* @return The index of the found element or -1 if none was found.
*/
private static int findFirstNotOneOfUs(StackTraceElement[] elements) {
int first = -1;
for (int i = 0; i < elements.length; i++) {
if (!elements[i].getClassName().equals(Callstack.class.getName())) {
first = i;
break;
}
}
return first;
}
} |
Partager