Original link: https://stackoverflow.com/questions/18900736/what-are-native-methods-in-java-and-where-should-they-be-used
Once you see a small example, it becomes clear:
Main.java:
public class Main {
public native int intMethod(int i);
public static void main(String[] args) {
System.loadLibrary("Main");
System.out.println(new Main().intMethod(2));
}
}
Main.c:
#include <jni.h>
#include "Main.h"
JNIEXPORT jint JNICALL Java_Main_intMethod(
JNIEnv *env, jobject obj, jint i) {
return i * i;
}
Compile and run:
On MacOS X
javac Main.java
javah -jni Main
gcc -I"$JAVA_HOME/include" -I"$JAVA_HOME/include/darwin" -o libMain.dylib -shared -fpic Main.c
On Windows 7 64bit, need to install MinGW64 to support GCC on 64bit system first.
https://sourceforge.net/projects/mingw-w64/files/Toolchains%20targetting%20Win64/Personal%20Builds/mingw-builds/4.9.1/threads-posix/seh/x86_64-4.9.1-release-posix-seh-rt_v3-rev0.7z/download
// Compile-only with -c flag. Output is Main.o
C:\ESE\C\JNI\smallE>gcc -c -I"%JAVA_HOME%\include" -I"%JAVA_HOME%\include\win32" Main.c
// Link into shared library "hello.dll"
C:\ESE\C\JNI\smallE>gcc -shared -o Main.dll Main.o
Output:
4
So it is clear that it allows you to:
- call a compiled dynamically loaded library (here written in C) with arbitrary assembly code from Java
- and get results back into Java
This could be used to:
- write faster code on a critical section with better CPU assembly instructions (not CPU portable)
- make direct system calls (not OS portable)
with the tradeoff of lower portability.
It is also possible for you to call Java from C, but you must first create a JVM in C: How to call Java functions from C++?
Example on GitHub for you to play with.