Alex
Alex

Reputation: 21

Is there a way to get the name of the source class/method that calls a second method?

For example, I want to have code like this:

class Class1
{
    Class2.print("Hello there.");
}

class Class2
{
    public void print(String message)
    {
        System.out.println("[method caller's name] : " + message);
    }
}

Class1 will call Class2's print method, which should print its caller's name followed by the message.

Upvotes: 2

Views: 94

Answers (3)

Robin
Robin

Reputation: 36601

You can use the Thread.getCurrentThread().getStackTrace() method. This returns you an array of StackTraceElement instances, on which you can ask for example the method name or class name.

This is similar to the response of Rajendran T's link, but does not create an exception to obtain the stack trace

Upvotes: 3

emesx
emesx

Reputation: 12755

Perhaps this will do

class Class1{
    public void doSomething(){
        Class2.print(this,"Hello there.");
    }
}

class Class2
{
    public static void print(Class1 caller, String message)
    {
        System.out.println("["+ caller +"] : " + message);
    }
}

Upvotes: 0

Rajendran T
Rajendran T

Reputation: 1553

May be this would help.

http://www.artima.com/forums/flat.jsp?forum=1&thread=1451

But I guess you should avoid such sort of things. Because creating new exception objects come at a cost.

Instead you shall pass down the caller as a print function argument.

Upvotes: -1

Related Questions