英文:
Kotlin does not allow T::class.java as a paramterized class type given to a java method
问题
以下是您要翻译的内容:
我正打算将我的一个服务变成通用的。然而,当我尝试将一个通用的 Kotlin 类型 T
传递给一个期望类的 Java 方法时,我未能成功。对于普通类型,我会这样做 MyClass::class.java
。对于通用类型,我尝试使用 T::class.java
。然而,这似乎是无效的。
无法将 'T' 用作具体化的类型参数。请改用类。
在这里发生的是 return mongoTemplate.aggregate(resolvedDocument, T::class.java).mappedResults[0]
服务:
@Service
class DocumentAggregator<T: Output>(
@Autowired
private val mongoTemplate: MongoTemplate
) {
fun <S: DocumentEntity> aggregate(document: S): T? {
val resolvedDocument: TypedAggregation<DocumentEntity> = // 逻辑
return mongoTemplate.aggregate(resolvedDocument, T::class.java).mappedResults[0]
}
}
英文:
I am about to make a service of mine generic. However I fail to do so when trying to pass a generic Kotlin type T
to a Java method that expects a class. Using normal types I'd do it like MyClass::class.java
. For the generic type I do T::class.java
. This however seems not to be valid.
Cannot use 'T' as reified type parameter. Use a class instead.
Happening here return mongoTemplate.aggregate(resolvedDocument, T::class.java).mappedResults[0]
Service:
@Service
class DocumentAggregator<T: Output>(
@Autowired
private val mongoTemplate: MongoTemplate
) {
fun <S: DocumentEntity>aggregate(document: S): T? {
val resolvedDocument: TypedAggregation<DocumentEntity> = // logic
return mongoTemplate.aggregate(resolvedDocument, T::class.java).mappedResults[0]
}
}
答案1
得分: 1
你应该尝试在泛型参数上添加reified
关键字,就像这样:
class DocumentAggregator<reified T: Output>
这样,类将在运行时存在。就像您添加额外的Class<T>
参数一样,只是使用了漂亮的Kotlin语法糖。
编辑:
关于注释,问题是您是否需要类上的泛型。可以编译的内容(感谢Willie指出错误)如下所示:
class Output
class DocumentAggregator(
private val mongoTemplate: Any?
) {
inline fun <S, reified T: Output> aggregate(document: S): T? {
return null
}
}
英文:
You should try adding the reified
keyword to the generic parameter, like this:
class DocumentAggregator<reified T: Output>
That ways the class will be present at runtime. Like when you added an additional Class<T>
parameter, just with the nice Kotlin syntax sugar.
EDIT:
Regarding the comments the question would be if you need the generics on the class. What compiles (thanks to Willie for pointing out the mistake) would be:
class Output
class DocumentAggregator(
private val mongoTemplate: Any?
) {
inline fun <S, reified T: Output>aggregate(document: S): T? {
return null
}
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论