Posts Tagged ‘dirty tips’
Where I come from?
Sometimes, inside of a java method, it’s needed to know which is the invoking method. I don’t know any documented procedure/technique to provide this information. So I use to develop a low performance piece of code based on an exception throwing and catching.
public void mockMethod() {
// Invoking Class
String invokingClass = "";
String invokingMethod = "";
// Where I come from?
try {
throw new Exception();
} catch (Exception e) {
// StackTrace to String
StringWriter sw = new StringWriter();
e.printStackTrace(new PrintWriter(sw));
// Split lines using "at " substring as separator
// Invoker is located at position 2 of the array
String[] lines = sw.toString().split("at ");
// a dot followed by a capital letter (ex. package.Class)
boolean dotCapital = false;
// find dotCapital position
int i = 0;
while (!dotCapital) {
dotCapital =
lines[2].charAt(i) == '.' &&
Character.isUpperCase(lines[2].charAt(i + 1));
i++;
}
// Class substring
while(!(lines[2].charAt(i) == '.')) {
invokingClass = invokingClass + lines[2].charAt(i);
i++;
}
i++;
// Method substring
while(!(lines[2].charAt(i) == '(')) {
invokingMethod = invokingMethod + lines[2].charAt(i);
i++;
}
}
System.out.println("Invoking class: " + invokingClass + "." + invokingMethod);
}
Inelegant but effective.