How to find out which method (java.class) called the current

Example. If I have two classes: A and B. both classes can call a method in C (example: init() method)

From C , how do we know where the call comes from (from class A or class B )?

+4
source share
4 answers

To do this correctly, you must provide a C-method with this information, for example, using an enumeration parameter or a class:

 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 to use stack trace. Look at Get the current stack trace in Java and use a second StackTraceElement from the top of the stack to get a method called the current one.

+3
source

Taken from somewhere on the Internet ...

 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(); } 
+1
source

This may be useful:

 StackTraceElement[] stackTraceElements = Thread.currentThread().getStackTrace(); 
  • you can use this to get the stack trace of the current thread in the StackTraceElement array, where the first element of the array is the most recent method call sequence on the stack

  • if the returned array has a nonzero length. StackTraceElement has methods like getClassName , getMethodName , etc. that can be used to find the name or class name of the caller.

+1
source

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 } } 
0
source

Source: https://habr.com/ru/post/1439097/


All Articles