Java interview preparation

    How to use the Java Native Interface (JNI) to call native code from Java

    Aliaksei Stadnik


    What is JNI

    The Java Native Interface (JNI) is a programming interface that allows Java code to call native code (i.e., code that is written in languages other than Java) and vice versa.

    This can be useful in situations where you need to call functionality that is not available in the Java platform, or when you need to interface with native libraries or other external components.

    To use the JNI to call native code from Java, you will need to do the following

    1. Write the native code that you want to call from Java. This code must be compiled into a native library (e.g., a dynamic shared object on Linux or macOS, or a dynamic-link library on Windows).

    2. Write a Java class that declares the native methods that will be called from the native code. These methods should be declared with the native modifier, and should not have an implementation.

    3. Use the System.loadLibrary method to load the native library that contains the native code.

    4. Call the native methods from your Java code using the standard method invocation syntax.

    Here is an example of how you might use the JNI to call native code from Java:

    carbon (17).png-icon

    Here is an example of the native code that might be used to implement the sayHello the method in the previous example

    carbon (18).png-icon

    This code is written in C, but it could also be written in C++ or any other language that is supported by the JNI. It includes the jni.h header file, which provides the necessary declarations and definitions for using the JNI.

    The Java_JNIExample_sayHello function is the implementation of the sayHello method declared in the Java code.

    It is given a JNIEnv pointer, which can be used to access the JNI functions, and a reference to the JNIExample object that called the method. In this example, the function simply prints a message to the console.

    To build this code into a native library, you will need to use a tool such as GCC on Linux or macOS, or the Visual C++ compiler on Windows.

    Once the native library has been built, you can use the System.loadLibrary method in your Java code to load the library and call the native method.