How to find out the class that called a method from another class?

4

I wanted to know if there is any way to get the class that called a method within that method. For example:

public class A {
    public void metodoA() {
        B.metodoB();
    }
}

public static B {
    public void metodoB() {
        //Aqui, de alguma forma, pegar a classe A, quando ela chamar
    }
}

Is there a possibility in Java, or would I need to send the class as a parameter to metodoB ?

    
asked by anonymous 30.08.2018 / 16:05

1 answer

4

There's no easy way to do this. Since the method does not mind knowing who called, but you could do something like this:

public class A {
    public void metodoA() {
        B.metodoB();
    }
}

public static B {
    public void metodoB() {
        StackTraceElement[] stackTrace = Thread.currentThread().getStackTrace();
        StackTraceElement element = stackTrace[2];
        System.out.println("O metodo que me chamou: " + element.getMethodName());
        System.out.println("O metodo esta na classe: " + element.getClassName());
    }
}
    
30.08.2018 / 16:23