使用泛型获取列表类:例如:List< Number> :: class [英] Getting Class of list with generic eg: List<Number>::class
问题描述
我有一个一般类型的类 Builder< T>
,它带有一个构造函数参数 Class< T>
可以保持周围的类型。这是一个我在java代码中使用很多的类,所以我不想更改签名。
当我尝试使用这样的构造函数时:
$ b
Builder< List< Number>>(List< Number> :: class)
我得到一个错误:类类只允许在类文字的左边
有什么办法解决这个问题?
我无法更改 Builder
的构造函数,太多的java类依赖它。
我明白整个类型的擦除问题,我真的只是想让编译器很开心。 解决方案
由于泛型类型擦除 List
类只有一个实现所有的通用实例。你只能得到一个对应于 List<>
类型的类,因此只能创建 Builder< List<>>
。
该构建器实例适合构建 列表。再次由于类型擦除,你可以通过未经检查的强制转换来自行决定: :class.java)as Builder< List< Number>>
Builder(List :: class.java as Class< List< Number>>)
另一种方法是创建内联通用辅助函数:
内联fun
并以如下方式使用它:
Builder< List<>>()
I have a generically typed class Builder<T>
that takes a constructor argument Class<T>
so I can keep the type around. This is a class that I use a lot in java code so I don't want to change the signature.
When I try to use the constructor like this:
Builder<List<Number>>(List<Number>::class)
I get an error: "Only classes are allowed on the left hand side of a class literal"
Any way to resolve this?
I can't change the constructor for Builder
, too many java classes rely upon it.
I understand the whole type erasure issue, I really just want to make the compiler happy.
Due to generic type erasure List
class has a single implementation for all its generic instantiations. You can only get a class corresponding to List<*>
type, and thus create only Builder<List<*>>
.
That builder instance is suitable for building a list of something. And again due to type erasure what that something is you can decide by yourself with the help of unchecked casts:
Builder(List::class.java) as Builder<List<Number>>
Builder(List::class.java as Class<List<Number>>)
Another approach is to create inline reified helper function:
inline fun <reified T : Any> Builder() = Builder(T::class.java)
and use it the following way:
Builder<List<Number>>()
这篇关于使用泛型获取列表类:例如:List< Number> :: class的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!