如何使用 Java 中的具体泛型调用 Kotlin 方法? [英] How can I call Kotlin methods with reified generics from Java?

查看:38
本文介绍了如何使用 Java 中的具体泛型调用 Kotlin 方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在 Kotlin 中有以下方法:

I have the following method in Kotlin:

inline fun <reified T> foo() {

}

如果我尝试像这样从 Java 调用它:

If I try to call this from Java like this:

myObject.foo();

或者像这样:

myObject.<SomeClass>foo();

我收到以下错误:

java: foo() 在 MyClass 中有私有访问权限

java: foo() has private access in MyClass

如何从 Java 调用 foo 方法?

How can I call the foo method from Java?

推荐答案

没有办法从 Java 中调用具有具体化类型参数的 Kotlin inline 函数,因为它们必须在调用点进行转换和内联(在您的情况下, T 应该替换为每个调用站点的实际类型,但是 inline 函数的编译器逻辑不仅仅是这个),Java 编译器是,意料之中,完全没有意识到这一点.

There's no way to call Kotlin inline functions with reified type parameters from Java because they must be transformed and inlined at the call sites (in your case, T should be substituted with the actual type at each call site, but there's much more compiler logic for inline functions than just this), and the Java compiler is, expectedly, completely unaware of that.

这篇关于如何使用 Java 中的具体泛型调用 Kotlin 方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆