Kotlin中如何实化泛型参数object类型与实现静态属性
问题解答
1. 实化object类型泛型参数的方案
可以通过inline + reified 实化泛型,配合Kotlin反射获取object单例实例,无需显式传入构造参数。
需要注意,使用objectInstance需要引入Kotlin反射依赖,Gradle配置参考:implementation "org.jetbrains.kotlin:kotlin-reflect:${kotlin_version}"
代码示例:
import kotlin.reflect.full.objectInstance interface SomeObject { val someProperty: String } object AnObject: SomeObject { override val someProperty = "someValue" } class GenericClass<O: SomeObject>(private val obj: O) { val someValue: String get() = obj.someProperty companion object { // 实化泛型的工厂方法,自动获取object实例 inline operator fun <reified O : SomeObject> invoke(): GenericClass<O> { val obj = O::class.objectInstance ?: throw IllegalArgumentException("泛型参数必须是object类型") return GenericClass(obj) } } } // 调用方式完全符合预期 fun main() { println(GenericClass<AnObject>().someValue) // 输出 someValue }
2. 其他实现类型级别静态属性的方案
如果不想引入反射,可以用以下两种方案:
方案1:伴生对象实现接口
interface SomeObject { val someProperty: String } class AnObject { // 伴生对象实现接口,属性天然属于类级别 companion object : SomeObject { override val someProperty = "someValue" } } class GenericClass<O> { companion object { inline val <reified O : AnObject.Companion> GenericClass<O>.someValue: String get() = O.someProperty } } fun main() { println(GenericClass<AnObject.Companion>().someValue) // 输出someValue }
方案2:@JvmStatic实现跨语言兼容的静态属性
如果需要和Java互操作,可以在伴生对象的属性上添加@JvmStatic注解,编译后会生成JVM层面的真实类静态字段:
class AnObject { companion object { @JvmStatic val someProperty = "someValue" } } // Java侧调用:AnObject.getSomeProperty() // Kotlin侧调用:AnObject.someProperty
内容的提问来源于stack exchange,提问作者ZeMoon
相关产品推荐
相关产品推荐

