Get name of current function in Kotlin
This article covers different ways to get name of the current function being executed in Kotlin.
1. Using Class.getEnclosingMethod() function
The trick is to call the Class.getEnclosingMethod() that returns a java.lang.reflect.Method object with almost every bit of information on immediately enclosing the underlying class’s function.
|
1 2 3 4 5 |
fun main() { val name = object{}.javaClass.enclosingMethod.name println("The current function is $name") } |
Output:
The current function is main
You can also define an inner class within a function to get Class reference, as shown below:
|
1 2 3 4 5 6 |
fun main() { class Main val name: String = Main::class.java.enclosingMethod.name println("The current function is $name") } |
Output:
The current function is main
2. Using Throwable.getStackTrace() function
Another approach is to get an array of stack trace elements representing the stack trace pertaining to a throwable by calling getStackTrace() on a Throwable instance.
The first element of the array represents the top of the stack, which is the last function invocation in the sequence.
|
1 2 3 4 5 |
fun main() { val name = Throwable().stackTrace[0].methodName println("The current function is $name") } |
Output:
The current function is main
You can also use the Exception class, which extends Throwable.
|
1 2 3 4 5 |
fun main() { val name = Exception().stackTrace[0].methodName println("The current function is $name") } |
Output:
The current function is main
3. Using Thread.getStackTrace() function
Another plausible way is to use the stack trace of a current thread, which returns an array of stack trace elements representing the stack dump of this thread.
The second element of the returned array of stack trace contains the stack frame of the current function.
|
1 2 3 4 5 |
fun main() { val name = Thread.currentThread().stackTrace[1].methodName println("The current function is $name") } |
Output:
The current function is main
That’s all about getting the name of the current function in Kotlin.
Thanks for reading.
To share your code in the comments, please use our online compiler that supports C, C++, Java, Python, JavaScript, C#, PHP, and many more popular programming languages.
Like us? Refer us to your friends and support our growth. Happy coding :)