How to figure out which class in Java is called a method?

How do I find a class called my method without passing any variables to the method?

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

Suppose an instance of class a calls an instance of class C and calls the same class for class B When class a calls method 1 of class C, I want it to print something like "class a calls me" and "class B calls me" when class B calls it

Solution

There is no simple way to do this, because usually a method does not need and should not pay attention to its call location If you write your method so that its behavior depends on its call location, your program will soon become an incomprehensible mess

However, this 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());
    }
}
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>