7

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".

4

2 に答える 2

14

通常、メソッドは呼び出された場所から気にする必要がないため、これを行う簡単な方法はありません。呼び出し元によって動作が異なるようにメソッドを作成すると、プログラムはすぐに理解できない混乱に変わります。

ただし、次に例を示します。

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());
    }
}
于 2012-08-28T14:18:10.307 に答える
6

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

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

于 2012-08-28T14:15:18.427 に答える