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.
You can use the
Thread.getCurrentThread().getStackTrace()method. This returns you an array ofStackTraceElementinstances, 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