25

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?

4

2 回答 2

32

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

于 2017-03-11T23:59:01.737 回答
0

inline没有类型参数声明的函数reified可以作为常规 Java 函数从 Java 中调用。但是使用reified类型参数声明的那些不能从 Java 调用。

即使您使用如下反射调用它:

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

你得到UnsupportedOperationException: This function has a reified type parameter and thus can only be inlined at compilation time, not called directly.

如果您有权访问函数的代码,则reified在某些情况下删除修饰符是可行的。在其他情况下,您需要对代码进行调整以克服类型擦除。

于 2021-03-25T15:00:10.643 回答