如何比较类和接口?

有人可以解释我如何比较KClasse-s和接口吗? 我知道如何检查类或接口是否相同,但我不明白如何检查A类是B类的超类。

interface IB {} interface IC : IB {} open class A {} open class B : A() {} open class C : B(), IC {} fun main(args: Array<String>) { if (B::class == B::class) { println("B class is equal to B class") } if (IB::class == IB::class) { println("IB interface is equal to IB interface") } if (A::class ??? B::class) { println("A class is parent of B class") } if (A::class ??? C::class) { println("A class is superclass of C class") } if (C::class ??? IC) { println("C class is implement IC interface") } if (IC ??? IB) { println("IC interface is implement IB interface") } } 

One Solution collect form web for “如何比较类和接口?”

Kotlin反射没有检索有关KClass层次结构的信息的API,因此检查一个KClass是否是另一个KClass超类或子类的唯一方法是比较相应的Java类:

 interface IB {} interface IC : IB {} open class A {} open class B : A() {} open class C : B(), IC {} fun main(args: Array<String>) { if (B::class == B::class) { println("B class is equal to B class") } if (IB::class == IB::class) { println("IB interface is equal to IB interface") } if (A::class.java.isAssignableFrom(B::class.java)) { println("A class is parent of B class") } if (A::class.java.isAssignableFrom(C::class.java)) { println("A class is superclass of C class") } if (IC::class.java.isAssignableFrom(C::class.java)) { println("C class is implement IC interface") } if (IB::class.java.isAssignableFrom(IC::class.java)) { println("IC interface is implement IB interface") } } 

更新:你也可以定义两个扩展函数,这将使这种检查更好一点:

 inline fun <reified L : Any, reified R : Any> isSubClassOf(): Boolean { return R::class.java.isAssignableFrom(L::class.java) } inline fun <reified L : Any, reified R : Any> isSuperClassOf(): Boolean { return L::class.java.isAssignableFrom(R::class.java) } fun main(args: Array<String>) { if (isSubClassOf<B, B>()) { println("B class is equal to B class") } if (isSubClassOf<IB, IB>()) { println("IB interface is equal to IB interface") } if (isSuperClassOf<A, B>()) { println("A class is parent of B class") } if (isSuperClassOf<A, C>()) { println("A class is superclass of C class") } if (isSubClassOf<C, IC>()) { println("C class is implement IC interface") } if (isSubClassOf<IC, IB>()) { println("IC interface is implement IB interface") } } 
  • 在android studio 3.0中导入项目代码类时出错
  • 如何实现从某个特定源获取的属性直到它直接在Kotlin中设置?
  • 本地委托属性和内联属性不支持增加赋值和增量
  • 在Kotlin中设置Guice绑定
  • 在蓝牙扫描期间找不到设备
  • 如何禁用Android Kotlin中的点按钮
  • 使用Mockito,我如何用val接口字段声明监听Kotlin类?
  • Gradle脚本Kotlin中的锅炉项目配置
  • kotlin函数返回null
  • Kotlin编译器返回:未解决的引用:Spring 5.0中的springframework
  • 打印中缀函数结果时,简单的kotlin示例打印kotlin.Unit
  • Kotlin language will be the best programming language for Android.