0

I want output com.iland.Action.LoginAction.doLogin()

The code should be effective for any class

for example

package com.iland.Action

Class LoginAction{

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

I would like to print dynamically fully qualified class name and the method name which is being executed.

  • 1
    Maybe this can help: http://stackoverflow.com/questions/442747/getting-the-name-of-the-current-executing-method – thetheodor Jan 29 '14 at 08:51

3 Answers3

4

Here is a code fragment that can help you.

StackTraceElement trace = new Throwable().getStackTrace()[0];
trace.getMethodName(); // returns method name
trace.getClassName(); // returns class name
Duncan Jones
  • 67,400
  • 29
  • 193
  • 254
AlexR
  • 114,158
  • 16
  • 130
  • 208
0

You can use this code inside your function body:

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

For more information on getStackTrace, refer this

Aman Arora
  • 1,232
  • 1
  • 10
  • 26
  • How to get package name – user3227094 Jan 29 '14 at 09:29
  • @AmanArora this code i am using while catching exception. Could you tell me how to get line number of exception code – xrcwrn Feb 19 '14 at 10:17
  • @xrcwrn Line number of exception code?.. Can you elaborate a bit? – Aman Arora Feb 19 '14 at 14:24
  • I am using this code for logging `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());` along with generating fully qualified class name and method name i want to get line number where exception is being thrown – xrcwrn Feb 20 '14 at 05:10
  • try this `Thread.currentThread().getStackTrace()[2].getLineNumber();` – Aman Arora Feb 20 '14 at 06:15
0

It will show you class name with packege and method name

  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
xrcwrn
  • 5,339
  • 17
  • 68
  • 129