问题描述
在许多使用JNI的示例中,我看到类似以下内容的东西:
In many examples of using JNI, I see something like:
class SampleClass {
static {
System.loadLibrary("somelib");
}
...
}
此特殊语法的目的是什么?为什么要使用它(而不仅仅是在类构造函数或类似的东西中使用?
What is the purpose of this special syntax? why using this (and not just in the class constructor or something like that?
推荐答案
我认为您将从书中获得最佳答案:
I think you will get the best answer from the book:
在哪里可以阅读:
通常,没有什么可以阻止您在类的方法内部加载库.方法,不是static
.但是在这种情况下,您必须确保在调用任何本机方法之前,先加载库(通过调用调用load或loadLibrary的方法).
In general, nothing prevents you from loading library inside method of a class. Method, that is not static
. But in that case, you have to make sure that you load library (by calling method that invokes load or loadLibrary) before you call any native method.
此外,如果您要加载另一个版本的库,而无需使用多个ClassLoader,则可以始终使用包装器代码.这样,您可以在本机代码实现之间动态切换.
Also, if you want to load another version of library, without playing with multiple ClassLoaders, you can always use wrapper code. This way, you can dynamically switch between native code implementations.
在这里看看:在JNI中动态加载库
这篇关于为什么要在Java中加载JNI是在静态初始值设定项中完成的?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!