简体   繁体   中英

How can I call Kotlin methods with reified generics from Java?

I have the following method in Kotlin:

inline fun <reified T> foo() {

}

If I try to call this from Java like this:

myObject.foo();

OR like this:

myObject.<SomeClass>foo();

I get the following error:

java: foo() has private access in MyClass

How can I call the foo method from Java?

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

The inline functions declared without reified type parameters can be called from Java as regular Java functions. But the ones declared with the reified type parameters are not callable from Java.

Even if you call it using the reflection like following:

Method method = MyClass.class.getDeclaredMethod("foo", Object.class);
method.invoke(new MyClass(), Object.class);

You get the UnsupportedOperationException: This function has a reified type parameter and thus can only be inlined at compilation time, not called directly.

If you have access to the code of the function, removing the reified modifier in some cases works. In other cases, you need to make adjustment to the code to overcome the type erasure.

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