Java
Summary - JNI
Combine native and JNIEnv to write a math native binding.
Summary - JNI
In this group you learned how to connect native code to Java. With native you declare a bodyless method; javac -h generates the C header; JNIEnv* lets C reach the JVM; System.loadLibrary loads the library.
Type mapping (int → I) and the C function naming (Java_Class_method) are the backbone of JNI. In modern Java 21 the FFM API is the safer, recommended path.
Exercise Write the JNI binder class
Define class JniBinder with String javaName and String signature fields and a JniBinder(String javaName, String signature) constructor that assigns them. A String cName() method returns "Java_" + javaName.replace(".", "_"). In main create JniBinder b = new JniBinder("NativeOps.sum", "(II)I"); and print System.out.println(b.cName() + " " + b.signature);.
Show example solution
class JniBinder {
String javaName;
String signature;
JniBinder(String javaName, String signature) {
this.javaName = javaName;
this.signature = signature;
}
String cName() {
return "Java_" + javaName.replace(".", "_");
}
}
public class Main {
public static void main(String[] args) {
JniBinder b = new JniBinder("NativeOps.sum", "(II)I");
System.out.println(b.cName() + " " + b.signature);
}
}
What you learned
You can now declare a native method, generate its header, build the C function name and derive the type signature. With System.loadLibrary you load the library and wrap errors with try.
New projects prefer the FFM API over JNI; but existing C libraries still require JNI. The combine task is the right moment to know both paths.
Exercise Add a describe method to JniBinder
Add a String describe() method to the JniBinder class above; it returns cName() + " " + signature. In main print it with System.out.println(b.describe());.
Show example solution
class JniBinder {
String javaName;
String signature;
JniBinder(String javaName, String signature) {
this.javaName = javaName;
this.signature = signature;
}
String cName() {
return "Java_" + javaName.replace(".", "_");
}
String describe() {
return cName() + " " + signature;
}
}
public class Main {
public static void main(String[] args) {
JniBinder b = new JniBinder("NativeOps.sum", "(II)I");
System.out.println(b.describe());
}
}
Test yourself
-
What is the modern alternative to JNI in Java?
- RMI
- Reflection
- FFM API
- Serialization
Show answer
FFM API — The FFM API is the modern alternative to JNI in Java 21.
-
Summarise the concepts
- native
- Bodyless method
- javac -h
- Header generation
- JNIEnv
- C interface
- FFM API
- Modern alternative
Next lesson: JMH