quinta-feira, março 04, 2004

Com uma rápida busca hoje, encontrei uma forma de buscar o nome do método que está atualmente em execução, no Java:

public String getCurrentMethodName() {
  return new Exception().getStackTrace()[1].getMethodName();
}


Funciona a partir da versão 1.4, quando as Exceptions passaram a ter o método getStackTrace(). Antes disso, é necessário fazer um parse na saída do printStackTrace():

public String getCurrentMethodName() {
ByteArrayOutputStream baos
= new ByteArrayOutputStream();

PrintWriter pw
= new PrintWriter(baos);
new Exception().printStackTrace(pw);
pw.flush();
String stackTrace
= baos.toString();
pw.close();

StringTokenizer tok
= new StringTokenizer(stackTrace, "\n");
String l
= tok.nextToken(); // 'java.lang.Throwable'
l = tok.nextToken(); // 'at ...getCurrentMethodName'
l = tok.nextToken(); // 'at ...<caller to getCurrentRoutine>'

// Parse line 3
tok = new StringTokenizer(l.trim(), " <(");
String t
= tok.nextToken(); // 'at'
t = tok.nextToken(); // '...<caller to getCurrentRoutine>'
return t;
}

Nenhum comentário: