android – Get name of current function in Kotlin-ThrowExceptions

Exception or error:

Update

How can I get function name which is currently being execute using Kotlin?

I’m trying to get the function name of the function which is currently being execute as below but it’s always coming as null

val funName = Object().`class`.enclosingMethod?.name;
How to solve:

I found one of the way:-

val name = object : Any() {

}.javaClass.enclosingMethod.name

Above code can also be refine as –

val name = object{}.javaClass.enclosingMethod.name

Edit because incorrect duplicate flag prevents a new answer:

A more Java way is this:

Thread.currentThread().stackTrace[1].methodName

but it takes ~47ms on my system compared with ~13ms for the object() based one: nearly 4 times slower.

###

There’s also another option if you don’t need the name to be discovered dynamically at runtime:

instance::method.name

Check below example on https://pl.kotl.in/1eREKeHh4:

fun main() {
    val test = Test()
    test.methodA()
    println("The name of method is [${test::methodA.name}]")
}

class Test {

    fun methodA() {
        logger(this::methodA.name)
        // do something important here...
    }

    fun logger(name: String) {
        println("Executing method [$name]")
    }
}

This way you can leverage all the “IDE intelligence” (renaming, searching for occurrences, etc.) but what’s important, all occurrences of instance::method.name are replaced by Kotlin to ordinary strings during compilation. If you decompile Kotlin-generated bytecode, you’ll see:

   public final void methodA() {
      Test var10001 = (Test)this;
      this.logger("methodA");
   }

Leave a Reply

Your email address will not be published. Required fields are marked *