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

Asked

Viewed 582 times

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 such a possibility in Java or I would need to send the class as a parameter to the metodoB?

  • 1

    B.metodoB(this.getClass()); ?

  • @Articuno as I finished in the question, this is the only way? There would be no way I ever catch from inside the metodoB?

  • 1

    What version of Java? Have JEP-259 in Java 9.

  • @Renan is version 8

  • You probably want to have different behaviors for each caller. Look for Strategy and hook method One of the two or the two together should solve your problem

1 answer

4


There is no easy way to do this. Since the method does not care 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());
    }
}
  • This is possible even if the class A calls a Thread.start()?

  • 3

    Yes. It works the same way.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.