I need to find the caller of a method. Is it possible using stacktrace or reflection?
相关问题
- Delete Messages from a Topic in Apache Kafka
- Jackson Deserialization not calling deserialize on
- How to maintain order of key-value in DataFrame sa
- StackExchange API - Deserialize Date in JSON Respo
- Difference between Types.INTEGER and Types.NULL in
Java 9 - JEP 259: Stack-Walking API
JEP 259 provides an efficient standard API for stack walking that allows easy filtering of, and lazy access to, the information in stack traces. Before Stack-Walking API, common ways of accessing stack frames were:
Using these APIs are usually inefficient:
In order to find the immediate caller's class, first obtain a
StackWalker
:Then either call the
getCallerClass()
:or
walk
theStackFrame
s and get the first precedingStackFrame
:Here is a part of the code that I made based in the hints showed in this topic. Hope it helps.
(Feel free to make any suggestions to improve this code, please tell me)
The counter:
And the object:
According to the Javadocs:
A
StackTraceElement
hasgetClassName()
,getFileName()
,getLineNumber()
andgetMethodName()
.You will have to experiment to determine which index you want (probably
stackTraceElements[1]
or[2]
).Sounds like you're trying to avoid passing a reference to
this
into the method. Passingthis
is way better than finding the caller through the current stack trace. Refactoring to a more OO design is even better. You shouldn't need to know the caller. Pass a callback object if necessary.Oneliner:
Note that you might need to replace the 2 with 1.