首页 > 解决方案 > 在 Kotlin IR 编译器中使用“this”关键字

问题描述

我正在为 Kotlin IR 编译器(版本 1.4.21)开发一个插件。该插件基于bnorm/debuglog (在此博客文章系列中有很好的描述)。

我想转换一个方法,以便它打印调用该函数的对象的类名,有点像这样:

原始方法:

@MyAnnotation
fun foo() {
    // Do something
}

变换方法:

@MyAnnotation
fun foo() {
    // Do something
    println(this::class.java.simpleName)
}

我的问题

我不知道如何使它与继承一起工作。

我试图function.parentClassOrNull?.name在我的 IR 编译器函数的覆盖版本中获取类名visitFunctionNew(...),但这会将“声明”类的名称(在源代码中明确声明该方法的类)硬编码到 print 语句中。

我还尝试找到并使用 Kotlinthis关键字的 IR 等效项,但没有成功。

这是我想要实现的示例:

源代码:

open class Superclass {
    @MyAnnotation
    fun foo() {
        // Do something
    }
}

class Subclass : Superclass()

执行时:

Superclass().foo()
>>> Superclass
Subclass().foo()
>>> Subclass

谢谢你的帮助!

标签: kotlin

解决方案


推荐阅读