how to figure out what class called a method in java?

旧街凉风 提交于 2020-03-18 12:02:55

问题


How do I figure out what class called my method without passing any variable to that 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 an instance of Class A calls an instance of class C and the same for class B. When class A calls class C method1 method, I want it to print something like "Class A called me", and when class B called it to print "Class B called me".


回答1:


There's no really easy way to do this, because normally a method doesn't and shouldn't need to care from where it is called. If you write your method so that it behaves differently depending on where it was called from, then your program is quickly going to turn into an incomprehensible mess.

However, here's 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());
    }
}



回答2:


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

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



来源:https://stackoverflow.com/questions/12161158/how-to-figure-out-what-class-called-a-method-in-java

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!