在 Kotlin 中,可以使用 KClass 类的 members 属性来获取类的所有成员函数,然后使用 isAnnotationPresent 方法判断成员函数是否有 Override 注解。

以下是一个示例代码:

import kotlin.reflect.full.declaredMemberFunctions
import kotlin.reflect.full.findAnnotation

fun main() {
    val myClass = MyClass()
    val methods = myClass::class.declaredMemberFunctions

    for (method in methods) {
        if (method.findAnnotation<Override>() != null) {
            println('Found method with @Override annotation: ${method.name}')
        }
    }
}

class MyClass {
    @Override
    fun myMethod() {
        // ...
    }
}

在上述代码中,我们通过 myClass::class.declaredMemberFunctions 获取到 MyClass 类的所有成员函数。然后使用 findAnnotation 方法来查找带有 Override 注解的方法,如果找到了,则打印方法名。

注意,findAnnotation 方法返回的是指定类型的注解实例,如果找不到对应的注解,则返回 null

Kotlin 反射获取 @Override 方法

原文地址: https://www.cveoy.top/t/topic/ol6w 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录