尝试将 Kotlin 具体化类型参数与库一起使用 class

Trying to use Kotlin reified type parameters with a library class

我正在使用 Kotlin 的 JGraphT 库,我想对我的图形进行参数化。但是,我尝试这样做的方式不起作用,因为 U 在编译时未定义并且不能用于反射。所以我收到错误消息 "Cannot use T as a reified type parameter. Use a class instead." 据我所知,具体化的类型参数可用于内联函数来解决此问题,但我看不出它对我有何帮助,尤其是知道我无法更改库代码。 任何想法将不胜感激。

class GraphManipulation<T,U> {
    val g = DefaultDirectedGraph<T, U>(U::class.java)
...}

问题不在于使用 DefaultDirectedGraph,而是 U 在您的 GraphManipulation class 中没有具体化。由于 classes 无法具体化 class 参数(还?),您需要将 class 作为构造函数参数:

class GraphManipulation<T,U>(private val uClass: Class<U>) {
    val g = DefaultDirectedGraph<T, U>(uClass)
}

reified可以帮助的地方是制作一个辅助方法

inline fun <T, reified U> GraphManipulation(): GraphManipulation<T,U> = GraphManipulation(U::class.java)