从 Kotlin 中的父类获取函数注解

问题描述 投票:0回答:1

假设我有以下情况:

abstract class Foo {

    abstract fun bar();

    fun baz() {
        println(this::bar.annotations)
    }

}

class Qux : Foo {

    @Annotation
    override fun bar() {
        ...
    }

}

当我尝试实现此功能时,它获取子类中定义的注释,而是获取父类中定义的注释。如果我没记错的话,Java 曾经做过前者,这就是我在这里尝试做的。我的目标输出是当

@Annotation
运行时打印
Qux#baz
。这在 kotlin 中可能吗?

使用

this::bar.javaClass.annotations
确实修复了它,以便我可以看到注释,但是我无法使用
is
获取注释的类型,至少如果可以的话,我不完全确定如何。

kotlin inheritance annotations
1个回答
0
投票

用以下内容替换原来的

println
行修复了问题:

...
    val method = this::class.java.getDeclaredMethod("bar")
    println(method.annotations)
...
© www.soinside.com 2019 - 2024. All rights reserved.