Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

java

class

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

like image 319
sheidaei Avatar asked Aug 28 '12 14:08

sheidaei


2 Answers

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());
    }
}
like image 192
Jesper Avatar answered Sep 28 '22 23:09

Jesper


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

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

like image 25
Subhrajyoti Majumder Avatar answered Sep 29 '22 00:09

Subhrajyoti Majumder