【发布时间】:2018-06-08 08:09:26
【问题描述】:
我尝试实现快速字段访问器功能,同时也想确保指定的类(字段的真正所有者)是接收者类型的超类,因此我写如下:
inline fun <A : B, reified B: Any> A.getProperty (name: String): Any {
return B::class.java.getDeclaredField(name).apply { isAccessible = true }.get(this)
}
但这让我在调用期间毫无意义地编写接收器类型:
// in SubClass
getProperty<SubClass, BaseClass>("fieldThatIsInBaseClass")
如果在当前类中定义了字段,令我惊讶的是它甚至不需要参数:
// in BaseClass
getProperty("fieldThatIsInBaseClass")
我也尝试将字段类型参数添加到函数中,但这会破坏上面的代码,并且在每种情况下都必须指定所有参数:
inline fun <A : B, reified B: Any, T> A.getProperty (name: String): T {
@Suppress("UNCHECKED_CAST")
return B::class.java.getDeclaredField(name).apply { isAccessible = true }.get(this) as T
}
以及这如何破坏事物的示例:
// in a class Example which declares the field
getProperty<Example, Example, Int>("someIntField")
类中定义字段的理想语法应该是:
getProperty<Int>("someIntField")
对于扩展某些基类的类:
getProperty<BaseClass, Int>("fieldThatIsInBaseClass")
这样的事情可能吗?
【问题讨论】:
-
标题中有“子类”,问题中有“超类”,第二个可能是正确的。
-
@AlexeyRomanov 谢谢,已修复
标签: generics reflection kotlin