Java native关键字

1,147 阅读1分钟

native关键字

使用native修饰的Java方法由其他语言实现,如C/C++,被编译成DLL后通过Java调用。所以native方法仅使用Java声明,不使用Java实现。例如Java Thread类中的native方法:

    /**
     * Tests if this thread is alive. A thread is alive if it has
     * been started and has not yet died.
     *
     * @return  <code>true</code> if this thread is alive;
     *          <code>false</code> otherwise.
     */
    public final native boolean isAlive();

为何使用native方法?

Java作为一种跨平台的语言(Write once, run anywhere)牺牲了对底层的控制。为了满足对底层控制的需求(如操作系统底层),Java通过native方法调用底层相关的C/C++代码(这些代码编译后的DLL中的方法)。选择使用native方法的通常情况如下:

  • 为了使用底层平台的某个特性,而这个特性不能通过Java API访问
  • 为了提升程序的性能,将时间敏感的部分代码替换为native方法(实现native方法的代码往往具有更高的效率)
  • 为了访问一个已有的、非Java语言编写的库

当然使用native方法也有不便之处:

  • 如果程序里使用了native方法,那么该程序就依赖于程序运行平台上的native方法的实现,破坏了Java本身的跨平台性
  • native方法实现中的错误在运行中(DLL的特点)可能导致JVM的崩溃

JNI与native方法

JNI是Java Native Interface的缩写,用于Java调用本地的C/C++代码。其与OS、JVM、Java的关系:

JNI调用本地C代码的流程: