kotlin - 在 Kotlin 中检查 isAssignableFrom 后如何转换泛型类型?
问题描述
请参阅示例:
class MyTypeAdapter<T : Throwable>
(private val gson: Gson, private val skipPast: TypeAdapterFactory) : TypeAdapter<T>() {
// :Throwable is needed to access the stackTrace field
}
private class ThrowableTypeAdapterFactory : TypeAdapterFactory {
override fun <T> create(gson: Gson, typeToken: TypeToken<T>): TypeAdapter<T>? {
if (Throwable::class.java.isAssignableFrom(typeToken.rawType)) {
return MyTypeAdapter<T>(gson, this) // compile error: Type argument is not within its bound
}
return null
}
}
所以在 Java 中我们有原始使用参数化类,但 Kotlin 不再允许它了。我试图从https://kotlinlang.org/docs/reference/generics.html中找到一些东西, 但找不到线索。请指教。
解决方案
由于类型擦除,您应该能够作弊:
return MyTypeAdapter<Throwable>(gson, this) as MyTypeAdapter<T>
看起来不对,但是类实际上不能根据T
.
或者如果 Kotlin 不会直接接受这个演员表(目前无法检查),比如
return (MyTypeAdapter<Throwable>(gson, this) as MyTypeAdapter<*>) as MyTypeAdapter<T>
甚至
return (MyTypeAdapter<Throwable>(gson, this) as Any) as MyTypeAdapter<T>
应该管用。
推荐阅读
- c - 在 Mac 上使用 += 时,静态 uint8_t 变量更改为不正确的值
- java - 这可以动态地将 onClick 功能分配给按钮吗?
- jquery - CSS - 目标 3rd div 但跳过子 div
- jdbc - 批量执行时如何查找失败的sql语句
- r - 为什么某些 R 包在新版本中不更改版本号
- html - 为什么我不能将下拉菜单放在按钮下?
- python - 有没有人在 google colab notebook 中成功嵌入了散景服务器?
- java - Azure IoT 中心:“签名证书信息与链元素不匹配”
- d3.js - D3 模块加载产生无法读取未定义的属性“文档”
- django - 如何使用 django 自定义表单保存多对多字段