为什么要在Java中加载JNI是在静态初始值设定项中完成的? [英] why loading JNI in java is done in static initializer?

查看:78
本文介绍了为什么要在Java中加载JNI是在静态初始值设定项中完成的?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在许多使用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:

Java™本机接口:程序员指南和规范,

在哪里可以阅读:

在可以调用本机方法print之前,本机库 工具必须加载.在这种情况下,我们加载本机 HelloWorld类的静态初始值设定项中的库. Java 虚拟机在运行之前会自动运行静态初始化程序 调用HelloWorld类中的任何方法,从而确保 在调用print本机方法之前,先加载本机库.

Before the native method print can be called, the native library that implements print must be loaded. In this case, we load the native library in the static initializer of the HelloWorld class. The Java virtual machine automatically runs the static initializer before invoking any methods in the HelloWorld class, thus ensuring that the native library is loaded before the print native method is called.

通常,没有什么可以阻止您在类的方法内部加载库.方法,不是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是在静态初始值设定项中完成的?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆