如何在Java中从该方法中查找方法名称? [英] How to find method name from within that method in Java?

查看:107
本文介绍了如何在Java中从该方法中查找方法名称?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道是否有办法知道在运行时执行的方法名称?

I was wondering if there is a way to know the method name being executed at run time?

例如,在私有空间内doSomething(String s)方法,我想知道我正在执行 doSomething(String s)方法。

For instance, inside a private void doSomething (String s) method, I'd like to know that I am executing the doSomething (String s) method.

推荐答案

从JDK1.5开始,你不需要Exception来获取StackTrace,你可以用
来获取它a href =http://www.rgagnon.com/javadetails/java-0420.html\"rel =noreferrer> Thread.currentThread()。getStackTrace()

Since JDK1.5, you don't need an Exception to get the StackTrace,
you can get it with Thread.currentThread().getStackTrace():

   public class Test2 {
     public static void main(String args[]) {
        new Test2().doit();
     }
     public void doit() {
        System.out.println(
           Thread.currentThread().getStackTrace()[1].getMethodName()); // output : doit
     }
   }

这篇关于如何在Java中从该方法中查找方法名称?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆