Kotlin原生界面

Kotlin是否使用了与Java相同的本地接口实现? 是否像在Java(对象传输的成本,字节流等)一样高效(或低效)?

在引擎盖下,实现是相同的,因为它将被转换为相同的Java代码。 这意味着它与Java代码一样高效。

使用本地方法nativeMethod()给出这个Kotlin类:

 class ExampleJni { companion object { init { System.loadLibrary("example-jni") } } external fun nativeMethod(): String } 

它将使用这个Java类的“相同”实现(转换不完全相同,但不会影响本地实现):

 public class ExampleJni { static { System.loadLibrary("hello-jni"); } public final native String nativeMethod(); } 

编辑

要更清楚的转换。 如果你反编译Kotlin代码,你可以看到它被转换成了两个类。 第一个包含本地方法:

 @dalvik.annotation.MemberClasses @kotlin.Metadata public final class ExampleJni { public static final ExampleJni$Companion Companion; public ExampleJni() { ... } static void <clinit>() { ... } @org.jetbrains.annotations.NotNull // Here you can see that the implementation is the same. public final native String nativeMethod() { ... } } 

另一个是与companion object相关的内部类。

 @dalvik.annotation.EnclosingClass @dalvik.annotation.InnerClass @kotlin.Metadata public final class ExampleJni$Companion { private ExampleJni$Companion() { ... } public ExampleJni$Companion(DefaultConstructorMarker) { ... } }