如何获取当前类中方法的名称

你好我的java类Toto,我有3个静态方法,当我在其中一个方法中时,我想知道如何在try catch bloc中获取并显示package.class.methode的名称? 我尝试过methodeA:

public static void methodeA(){ try{ system.out.println("I do something"); } catch(Exception e){ system.out.println("failed" +e.getClass().getMethods().toString()); } 

但它不起作用,我怎么也可以在试试中显示它? 谢谢

e.printStackTrace(); – 这将打印整个exceptionstracktrace – 即所有方法+行号。

 e.printStackTrace(); 
 e.getStackTrace()[0].getMethodName(); 

e.getStackTrace()[0] .getMethodName()

您可以使用以下示例:

 public class A { public static void main(String args[]) { new A().intermediate(); } void intermediate() { new A().exceptionGenerator(); } void exceptionGenerator() { try { throw new Exception("Stack which list all calling methods and classes"); } catch( Exception e ) { System.out.println( "Class is :" + e.getStackTrace()[1].getClassName() + "Method is :" + e.getStackTrace()[1].getMethodName()); System.out.println("Second level caller details:"); System.out.println( "Class is :" + e.getStackTrace()[2].getClassName() + "Method is :" + e.getStackTrace()[2].getMethodName()); } } } 

您是否注意到您的exception堆栈跟踪中已有信息?

实际上,Exception类提供了一个getStackTrace()方法,它返回一个StacktraceElement数组。 这些元素中的每一个都为您提供了类名,方法名和其他一些细节。 如果你找到三种方法中的一种,你可以做的就是查看这个数组,瞧!

但是,请注意,如果在代码上使用混淆器,则检测方法名称可能会失败。

首选…..

 catch(Exception e) { e.printStackTrace(); } 

或者(不是明智的选择,因为你不知道抛出了什么exception,你没有打印堆栈跟踪元素)。

 catch(Exception e) { System.out.println(e.getStackTrace()[0].getMethodName()); } 

如果抛出exception,则会影响您的性能。 不需要抛出exception,

 public class AppMain { public static void main(String[] args) { new AppMain().execute(); } private void execute(){ RuntimeException exception = new RuntimeException(); StackTraceElement currentElement = exception.getStackTrace()[0]; System.out.println(currentElement.getClassName()); System.out.println(currentElement.getMethodName()); } }