简体   繁体   中英

Kotlin does not allow T::class.java as a paramterized class type given to a java method

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]
    }
}

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
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM