How to find out which class is called a method in java?

How can I define a class called my method without passing any variable to this method? let's say we have something like this:

Class A{} Class B{} Class C{ public void method1{} System.out.print("Class A or B called me"); } 

let's say that an instance of class A calls an instance of class C and the same for class B. When class A calls the method of class C method1, I want it to print something like "Class A called me" and when class B calls it to type "Class B, called me."

+4
source share
2 answers

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()); } } 
+7
source

You can use Thread.currentThread().getStackTrace()

It returns an array [StackTraceElements][1] , which represents the current trace of the program stack.

+6
source

All Articles