Table of Contents
Java Native Interface (JNI)
Return to Java, Foreign Function Interface (FFI)
Overview
Java Native Interface (JNI) is a framework that enables Java code running in the Java Virtual Machine (JVM) to interact with applications and libraries written in other languages, primarily C, C++, and assembly. JNI allows Java code to call native methods and vice versa, facilitating interoperability between Java and native code.
Key Features
- **Calling Native Methods:** Java code can invoke functions implemented in native libraries using JNI. This allows Java to access platform-specific features or leverage existing native code.
- **Embedding JVM:** Native applications can embed the JVM, allowing them to execute Java code and access Java libraries.
- **Data Exchange:** JNI provides mechanisms for exchanging data between Java and native code, including primitive types, objects, arrays, and strings.
- **Exception Handling:** JNI allows exceptions thrown in Java code to be caught and handled in native code, and vice versa.
- **Reflection:** JNI provides limited reflection capabilities, allowing native code to inspect and manipulate Java classes and objects.
Resources
Code Example
**Java (Calling Native Method):**
```java public class Example {
// Declare a native method private native void sayHello();
static { // Load the native library System.loadLibrary("example"); }
public static void main(String[] args) { new Example().sayHello(); }} ```
**C (Implementing Native Method):**
```c
- include <jni.h>
- include <stdio.h>
JNIEXPORT void JNICALL Java_Example_sayHello(JNIEnv *env, jobject obj) {
printf("Hello from C!\n");} ```
In this example, the Java code declares a native method `sayHello` and loads a native library named `example`. The C code implements this method, which simply prints a message to the console.