Kotlin不允许将T::class.java作为参数化的类类型传递给Java方法。

huangapple go评论70阅读模式
英文:

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 &#39;T&#39; as reified type parameter. Use a class instead.

Happening here return mongoTemplate.aggregate(resolvedDocument, T::class.java).mappedResults[0]

Service:

@Service
class DocumentAggregator&lt;T: Output&gt;(
    @Autowired
    private val mongoTemplate: MongoTemplate
) {
    fun &lt;S: DocumentEntity&gt;aggregate(document: S): T? {
        val resolvedDocument: TypedAggregation&lt;DocumentEntity&gt; = // 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&lt;reified T: Output&gt;

That ways the class will be present at runtime. Like when you added an additional Class&lt;T&gt; 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 &lt;S, reified T: Output&gt;aggregate(document: S): T? {
        return null
    }
}

huangapple
  • 本文由 发表于 2020年9月10日 07:09:03
  • 转载请务必保留本文链接:https://go.coder-hub.com/63820684.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定