【发布时间】:2021-10-19 11:22:02
【问题描述】:
假设以下 (jdbc) 存储库:
interface Repo : CrudRepository<MyType, Long> {
@Query("select * from blabla")
fun abc(): List<MyType>
}
对于 abc() 方法和父接口中包含的方法,Repo 接口的自动生成运行时实现知道如何将结果集序列化为 MyType 的实例,但受到某些限制。
Spring 如何在运行时访问泛型参数的类型信息?它如何仅根据接口中提供的类型信息来创建正确运行时类型的列表?
我的理解是,我不会从下面的mapV1() 之类的签名中获得足够的信息来实例化我的结果,因此我需要引入第二个类型为Class<T> 的参数,如mapV2() 所示:
class Mapper {
fun <T> mapV1(source: Any): T {
/*
try to instantiate a result
of type T reflectively
*/
}
fun <T> mapV2(source: Any, klass: Class<T>): T {
/*
try to instantiate a result
of type T reflectively
*/
}
}
Spring 以某种方式避免了这个问题。
【问题讨论】:
标签: java kotlin generics reflection spring-data