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.
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...
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.
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()
class A {
B().foo()
}
class B {
fun foo() {
val className = Throwable().stackTrace[1].className.substringAfterLast('.')
Log.d(TAG, className) //prints "A"
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With