---
title: "方法内 如何得到当前方法名"
author: "linsl"
date: "2010-12-08T12:06:23Z"
tags: []
categories: ["编程语言"]
slug: "untitled"
draft: false
lastmod: "2010-12-08T12:06:23Z"
id: 836530
url: "https://linsl.iteye.com/blog/836530"
---

public class MyTest {

    public static void main(String args\[]) {

      new MyTest().doit();

    }

    public void doit() {

      System.out.println

         (new Exception().getStackTrace()\[0].getMethodName());

    }

}

 

 

JDK1.5, a new technique is available.

```
public class Test {
 public static void main(String args[]) {
    trace(Thread.currentThread().getStackTrace());
    new Test().doit();
    trace(Thread.currentThread().getStackTrace());
 }
 public void doit() {
    trace(Thread.currentThread().getStackTrace());
    doitagain();
  }
 public void doitagain() {
    trace(Thread.currentThread().getStackTrace());
  }

 public static void trace(StackTraceElement e[]) {
   boolean doNext = false;
   for (StackTraceElement s : e) {
       if (doNext) {
          System.out.println(s.getMethodName());
          return;
       }
       doNext = s.getMethodName().equals("getStackTrace");
   }
 }
}
```

 

```
main
doit
doitagain
main
```

```
参考: http://www.rgagnon.com/javadetails/java-0420.html
```