gpt4 book ai didi

java - 为什么在java中加载JNI是在静态初始化程序中完成的?

转载 作者:行者123 更新时间:2023-11-30 02:22:01 24 4
gpt4 key购买 nike

在许多使用 JNI 的示例中,我看到类似以下内容:

class SampleClass {
static {
System.loadLibrary("somelib");
}
...
}

这种特殊语法的目的是什么?为什么使用这个(而不仅仅是在类构造函数或类似的东西中?

最佳答案

我想你会从书中得到最好的答案:

Java™ Native Interface: Programmer’s Guide and Specification, The

您可以在哪里阅读:

Before the native method print can be called, the native library thatimplements print must be loaded. In this case, we load the nativelibrary in the static initializer of the HelloWorld class. The Javavirtual machine automatically runs the static initializer beforeinvoking any methods in the HelloWorld class, thus ensuring that thenative library is loaded before the print native method is called.

一般来说,没有什么可以阻止您在类的方法中加载库。方法,不是静态。但在这种情况下,您必须确保在调用任何 native 方法之前加载库(通过调用调用 load 或 loadLibrary 的方法)。

此外,如果您想加载另一个版本的库,而不需要使用多个类加载器,您始终可以使用包装器代码。这样,您就可以在 native 代码实现之间动态切换。

看这里:dynamic loading of library in JNI

关于java - 为什么在java中加载JNI是在静态初始化程序中完成的?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46538227/

24 4 0
文章推荐: java - 在圆上绘制 N 个等距点,只给出一个点
文章推荐: Android Facebook 分享对话框回调
文章推荐: java - ArrayList 的比较器不能正常工作