There is no easy way to do this, because usually a method does not require and should not care about where it is called. If you write your method so that it behaves differently depending on where it was called from, your program will quickly turn into an incomprehensible mess.
However, here is an example:
public class Prut { public static void main(String[] args) { example(); } public static void example() { StackTraceElement[] stackTrace = Thread.currentThread().getStackTrace(); StackTraceElement element = stackTrace[2]; System.out.println("I was called by a method named: " + element.getMethodName()); System.out.println("That method is in class: " + element.getClassName()); } }
source share