Example: If I have two classes: A and B. both class can call a method in C (example: the init()
method)
From C, how do we know where the call is from (from Class A or Class B) ?
Example: If I have two classes: A and B. both class can call a method in C (example: the init()
method)
From C, how do we know where the call is from (from Class A or Class B) ?
To do it right, you should provide C's method with that information, for example via an enum or class parameter:
public void init(Object otherArg, Class<?> caller) {
...
}
or
public void init(Object otherArg, CallerEnum caller) {
...
}
But if you don't care, there is another way using the stack trace. Have a look at Get current stack trace in Java and use the second StackTraceElement from the top of the stack to get the method that called the current one.
This may be useful:
StackTraceElement[] stackTraceElements = Thread.currentThread().getStackTrace();
you can use this to get the stack trace of the current thread in a StackTraceElement
array where the first element of the array is the most recent method invocation sequence on the stack
provided the returned array is of non-zero length.
StackTraceElement
has methods like getClassName
, getMethodName
, etc., which one can use to find the caller class name or method name.
Taken from somewhere of the web...
private static final int CLIENT_CODE_STACK_INDEX;
static {
// Finds out the index of "this code" in the returned stack trace - funny but it differs in JDK 1.5 and 1.6
int i = 0;
for (StackTraceElement ste : Thread.currentThread().getStackTrace()) {
i++;
if (ste.getClassName().equals(MyClass.class.getName())) {
break;
}
}
CLIENT_CODE_STACK_INDEX = i;
}
public static String getCurrentMethodName() {
return Thread.currentThread().getStackTrace()[CLIENT_CODE_STACK_INDEX].getMethodName();
}
public static String getCallerMethodName() {
return Thread.currentThread().getStackTrace()[CLIENT_CODE_STACK_INDEX+1].getMethodName();
}
I found an easier solution (for me :D )
public <T> void init(Class<T> clazz) {
if (!clazz.getSimpleName().equals("MyClassName")) {
// do something
}else{
// do something
}
}