How to recognize the calling class?

how can i find out which class / method called the actual method?

+3
source share
6 answers

You can try to throw an exception to get its stack.

Throwable t = new Throwable();
StackTraceElement[] stackTraceElements = t.getStackTrace();

Now stackTraceElement[0]contains the caller of the current method.

But be careful (from Throwable.getStackTrace () ):

, , . , , . , , , printStackTrace.

+8

, :

StackTraceElement element=Thread.currentThread().getStackTrace()[3];
String className=element.getClassName();
String methodName=element.getMethodName();

[3] , :

[0] - Thread.dumpThreads()

[1] - Thread.getStackTrace()

[2] -

[3] - ,

+5

, - . . , JVM Java .

Class callerClass = sun.reflect.Reflection.getCallerClass(2);
+1

, .

, , ( , ).

0

. Netbeans , .

, , () .

0

b yishai:

, , , . , : , " ", , , .

Java , , . , , , .

But if you do this because your function will behave differently depending on where it was called from, for example, “if called from class X, update client data else, if called from employee update data Y,” or something like that: Really a really bad idea. Pass a parameter or write individual functions.

0
source

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


All Articles