获取Kotlin中的函数名称

Sur*_*rma 16 android kotlin

更新

如何获取当前正在执行的函数名Kotlin

我正在尝试获取当前正在执行的函数的函数名称,如下所示,但它始终为null

val funName = Object().`class`.enclosingMethod?.name;
Run Code Online (Sandbox Code Playgroud)

Sur*_*rma 23

我找到了一条路: -

val name = object : Any() {

}.javaClass.enclosingMethod.name
Run Code Online (Sandbox Code Playgroud)

以上代码也可以改进为 -

val name = object{}.javaClass.enclosingMethod.name
Run Code Online (Sandbox Code Playgroud)

  • 我想知道性能成本是多少? (3认同)
  • 安全起见:object{}.javaClass.enclosureMethod?.name (3认同)

dom*_*nik 18

如果您不需要在运行时动态发现名称,还有另一种选择:

instance::method.name
Run Code Online (Sandbox Code Playgroud)

https://pl.kotl.in/1ZcxQP4b3上查看以下示例:

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

class Test {
    fun methodA() {
        println("Executing method ${this::methodA.name}")
        println("Executing method ${::methodA.name} - without explicit this")
    }
}
Run Code Online (Sandbox Code Playgroud)

执行后main()你会看到:

Executing method methodA
Executing method methodA - without explicit this
The name of method is methodA
Run Code Online (Sandbox Code Playgroud)

通过这种方式,您可以利用所有“IDE 智能”(重命名、搜索出现次数等),但重要的instance::method.name是,在编译过程中,Kotlin 将所有出现次数替换为普通字符串。如果您反编译 Kotlin 生成的字节码,您将看到:

public final void main() {
    Test test = new Test();
    test.methodA();
    String var2 = "The name of method is " + "methodA"; // <--- ordinary string, no reflection etc.
    boolean var3 = false;
    System.out.println(var2);
}
Run Code Online (Sandbox Code Playgroud)