【发布时间】:2021-04-10 17:39:49
【问题描述】:
我创建了一个相当于 TypeReference<T> 的 Kotlin,如下所示:
abstract class TypeReference<T> : Comparable<T> {
val type: Type get() = getGenericType()
val arguments: List<Type> get() = getTypeArguments()
final override fun compareTo(other: T): Int {
return 0
}
private fun getGenericType(): Type {
val superClass = javaClass.genericSuperclass
check(superClass !is Class<*>) {
"TypeReference constructed without actual type information."
}
return (superClass as ParameterizedType).actualTypeArguments[0]
}
private fun getTypeArguments(): List<Type> {
val type = getGenericType()
return if (type is ParameterizedType) {
type.actualTypeArguments.toList()
} else emptyList()
}
}
为了获取泛型类型及其参数的Class<*>,我还创建了以下扩展函数(这就是我认为问题所在,因为这是堆栈跟踪失败的地方)。
fun Type.toClass(): Class<*> = when (this) {
is ParameterizedType -> rawType.toClass()
is Class<*> -> this
else -> Class.forName(typeName)
}
我正在像这样进行单元测试:
@Test
fun `TypeReference should correctly identify the List of BigDecimal type`() {
// Arrange
val expected = List::class.java
val expectedParameter1 = BigDecimal::class.java
val typeReference = object : TypeReference<List<BigDecimal>>() {}
// Act
val actual = typeReference.type.toClass()
val actualParameter1 = typeReference.arguments[0].toClass()
// Assert
assertEquals(expected, actual)
assertEquals(expectedParameter1, actualParameter1)
}
我认为问题在于它抛出的扩展函数else -> Class.forName(typeName):
java.lang.ClassNotFoundException: ?扩展 java.math.BigDecimal
有没有更好的方法来获取Type 的Class<*>,即使它们是泛型类型参数?
【问题讨论】:
标签: kotlin