【问题标题】:Dynamically printing fully qualified class name along with method name [duplicate]动态打印完全限定的类名和方法名[重复]
【发布时间】:2014-02-20 23:05:28
【问题描述】:

我要输出com.iland.Action.LoginAction.doLogin()

代码应该对任何类都有效

例如

package com.iland.Action

Class LoginAction{

  void doLogin()
  {
      System.out.println("");//what contens should be printed in sop
  }
}

我想动态打印完全限定的类名和正在执行的方法名。

【问题讨论】:

标签: java


【解决方案1】:

这是一个可以帮助您的代码片段。

StackTraceElement trace = new Throwable().getStackTrace()[0];
trace.getMethodName(); // returns method name
trace.getClassName(); // returns class name

【讨论】:

  • 我们可以根据需要获得完全限定的方法名称吗com.iland.Action.LoginAction.doLogin()
【解决方案2】:

您可以在函数体内使用此代码:

String Name=this.getClass().toString();
String fullName=Name.substring(Name.lastIndexOf(" ")+1);
System.out.println(fullName);// fully qualified class name.
System.out.println(fullName.substring(0,fullName.lastIndexOf(".")));// package name
System.out.println(fullName+new Throwable().getStackTrace()[0].getMethodName());// fully qualified method name

有关 getStackTrace 的更多信息,请参阅this

【讨论】:

  • 如何获取包名
  • @user3227094 请查看编辑。
  • @AmanArora 这是我在捕获异常时使用的代码。你能告诉我如何获取异常代码的行号
  • @xrcwrn 异常代码行号?..你能详细说明一下吗?
  • 我正在使用此代码记录 try{.........} catch (SQLException e) { status = "failure"; System.out.println("Exception " + e); LogErrorBusiness.log(new Throwable().getStackTrace()[0].getClassName(), new Throwable().getStackTrace()[0].getMethodName(), e.toString()); 以及生成完全限定的类名和方法名,我想获取抛出异常的行号
【解决方案3】:

它会显示类名以及包和方法名

  System.out.println(new Throwable().getStackTrace()[0].getClassName());//  class name
        System.out.println(new Throwable().getStackTrace()[0].getMethodName());// method name
        StackTraceElement[] stackTraceElements = Thread.currentThread().getStackTrace();
        System.out.println(stackTraceElements[1].getClassName());//class name
        System.out.println(stackTraceElements[1].getMethodName());//method name

【讨论】:

    猜你喜欢
    • 2017-03-17
    • 1970-01-01
    • 2020-11-12
    • 2010-12-06
    • 2012-10-01
    • 2021-03-25
    • 2011-11-08
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多