Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check which class has called function

Tags:

java

How can I check which class has called my method?

For example: If Class A uses the MethodB in the Class C than, the function should do something else than the function would do, if Class B calls the MethodB.

I can't add a boolean or something like that to the method.

like image 569
Christian Avatar asked Nov 08 '13 13:11

Christian


4 Answers

There's no good way of doing this - and it's fundamentally a bad design, IMO. If ClassA and ClassB want different things to happen, they should call different methods.

The only time this is reasonable in my experience is when trying to work out a simple way of initializing loggers, where basically you want the calling class name to be part of the logger name. One horrible way of doing that is to throw and catch an exception, then look at its stack trace. But avoid if possible...

like image 180
Jon Skeet Avatar answered Oct 17 '22 15:10

Jon Skeet


It is possible to find the name of the class for a calling method. Here is how you can achieve it.

class A {

    public void testMethodCall() {
        new C().testMethod();
    }
}

class B {
  public void testMethodCall() {
      new C().testMethod();
  }
}

class C {

    public void testMethod() {
        System.out.println("Called from class : " +Thread.currentThread().getStackTrace()[2].getClassName());
    }
}
public class Test
{
    public static void main(String args[]) {
        A a = new A();
        B b = new B();
        a.testMethodCall();
        b.testMethodCall();
    }

}

Output

Called from class : A

Called from class : B

You can use this sample code to adapt to your need.

like image 34
Juned Ahsan Avatar answered Oct 17 '22 15:10

Juned Ahsan


StackTraceElement[] stackTraceElements = Thread.currentThread().getStackTrace()  

javadoc:

The last element of the array represents the bottom of the stack, which is the least recent method invocation in the sequence.

and the documentation of what you can get from each StackTraceElement

http://docs.oracle.com/javase/7/docs/api/java/lang/StackTraceElement.html

getClassName()
getFileName()
getLineNumber() 
getMethodName()
like image 4
RamonBoza Avatar answered Oct 17 '22 15:10

RamonBoza


class A {
     B().foo()
}

class B {
     fun foo() {
         val className = Throwable().stackTrace[1].className.substringAfterLast('.')
         Log.d(TAG, className) //prints "A"
     }
}
like image 1
Soroush Lotfi Avatar answered Oct 17 '22 14:10

Soroush Lotfi