0

我希望能够打印调用方法名称而不是包含打印方法的方法。有没有办法做到这一点?

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();

}
4

1 回答 1

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();
}
于 2013-08-30T23:35:01.727 回答