D
D
Dmitry Vatlin2019-11-16 16:31:17
Java
Dmitry Vatlin, 2019-11-16 16:31:17

How to find out the name of the calling method through reflection in Java?

We need to write a function that would return the full name of the class and the name of the calling function at runtime. I get the full class name, but I don't know how to use the data obtained with .getDeclaredMethods() to determine the name of the calling method.

Class<?> c = new Object() { }.getClass().getEnclosingClass(); // объект нужного класса
String nameFullleClass = c.getName(); // полное имя класса
Method[] methods = c.getDeclaredMethods(); // массив с именами всех методов

Answer the question

In order to leave comments, you need to log in

1 answer(s)
S
Sergey Gornostaev, 2019-11-16
@2tlin

StackTraceElement ste = Thread.currentThread().getStackTrace()[2];
System.out.printf("%s.%s()", ste.getClassName(), ste.getMethodName());

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question