我希望能够打印调用方法名称,而不是包含print方法的方法。有没有办法做到这一点?
private void printOrderNumber() {
String methodName = Thread.currentThread().getStackTrace()[1].getMethodName();
System.out.println(methodName);
try {
PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter("variableOutput.txt", true)));
out.println(methodName);
out.println(var1);
out.println("");
out.close();
} catch (IOException e) {
//oh noes!
}
}
private void order1(){
printOrderNumber();
}
答案 0 :(得分:2)
只需遍历堆栈跟踪
import java.lang.*;
public class StackTraceElementDemo {
public static void main(String[] args) {
function1();
}
public static void function1()
{
new StackTraceElementDemo().function2();
}
public void function2()
{
int i;
System.out.println("method name : ");
// print stack trace
for( i = 1; i <= 3; i++ ) {
System.out.println(Thread.currentThread().getStackTrace()[i].
getMethodName());
}
}
}
这部分错了:
第二种方式是使用class.getDeclaredMethods()
:
for (Method method : Name.class.getDeclaredMethods()) {
String name = method.getName();
}