[英]Why we write NextActivity::class.java although this is a kotlin class?
[英]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
。 然而,這似乎是無效的。
Cannot use 'T' as reified type parameter. Use a class instead.
發生在這里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> = // logic
return mongoTemplate.aggregate(resolvedDocument, T::class.java).mappedResults[0]
}
}
您應該嘗試將reified
關鍵字添加到泛型參數中,如下所示:
class DocumentAggregator<reified T: Output>
這樣該類將在運行時出現。 就像您添加額外的Class<T>
參數一樣,只需使用漂亮的 Kotlin 語法糖即可。
編輯:關於評論,問題是您是否需要類上的泛型。 編譯(感謝威利指出錯誤)將是:
class Output
class DocumentAggregator(
private val mongoTemplate: Any?
) {
inline fun <S, reified T: Output>aggregate(document: S): T? {
return null
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.