user650521
user650521

Reputation: 583

How to get the name of called method in java

Suppose I have a method like this

Calculator calc;
public void testMethod(){
-----
----
Calc.add(1,2);
-----
-------
}

Now I want print Calculator.add at the end of the function, i.e i want to print the classname.printname at the end of the function. The printing should be generic enough that I can use the same for other methods as well. How to achieve this goal.

Thanks in advance

Upvotes: 2

Views: 2783

Answers (4)

Siddu
Siddu

Reputation: 77

Check below lines by changing index value:

 System.out.println("Name of Caller method:" 
+ new Throwable().getStackTrace()[1].getMethodName());

    System.out.println("Name of Current method:" 
+ new Throwable().getStackTrace()[0].getMethodName());
            

Upvotes: 0

jahroy
jahroy

Reputation: 22692

As the very simplest approach, remember you can always call this.getClass().getName():

class SimpleCalculator {

    public int add(int a, int b) {
        System.out.println(this.getClass().getName() +
                " - adding " + a + " and " + b);
        return a + b;
    }
}

Another common approach is to use a logging library like Log4J.

The class you'd be using is Logger

You configure Log4J to write to a certain file.

Each class declares a Logger object that prints messages to a file.

Each message begins with the name of the class that generated the message.

class SimpleCalculator {

    Logger calcLogger = Logger.getLogger(SimpleCalculator.class);

    public int add(int a, int b) {
        calcLogger.debug("add - adding " + a + " and " + b);
        return a + b;
    }
}

... or you could use a method like @urir suggests.

... or you could get crazy and use AOP.

Upvotes: 2

mahipal purohit
mahipal purohit

Reputation: 264

user Calculator.getClass().getName());for finding name of class and Calculator.getMethod();

or use System.out.println( "I was called by " + e.getStackTrace()[1].getClassName() + "." + e.getStackTrace()[1].getMethodName() + "()!" );

Upvotes: 0

urir
urir

Reputation: 2025

private static final int CLIENT_CODE_STACK_INDEX;

static {
    // Finds out the index of "this code" in the returned stack trace - funny but it differs in JDK 1.5 and 1.6
    int i = 0;
    for (StackTraceElement ste : Thread.currentThread().getStackTrace()) {
        i++;
        if (ste.getClassName().equals(Resource.class.getName())) {
            break;
        }
    }
    CLIENT_CODE_STACK_INDEX = i;
}

public static String getCurrentMethodName() {
    return Thread.currentThread().getStackTrace()[CLIENT_CODE_STACK_INDEX].getMethodName();
}
public static String getCallerMethodName() {
    return Thread.currentThread().getStackTrace()[CLIENT_CODE_STACK_INDEX+1].getMethodName();
}

Upvotes: 2

Related Questions