Native Modifier
native is a modifier applicable only for methods. It cannot be applied anywhere else. Methods implemented in non-Java languages (like C or C++) are called native methods or foreign methods.
Objectives of Native Keyword
- Improve system performance
- Enable machine-level or memory-level communication
- Use existing legacy non-Java code
Pseudo Steps to Use Native
- Load native library
- Declare native method
- Invoke native method
Example
class Test {
static {
System.loadLibrary("native_library");
}
public native void m();
}
class Client {
public static void main(String[] args) {
Test t = new Test();
t.m();
}
}
For native methods, implementation is already available in languages like C/C++, so we are not responsible for providing implementation in Java. Hence, native methods must end with a semicolon.
public native void m(); // Valid
public native void m(){} // Invalid
Important Rules
- native + abstract → ❌ Not allowed
- native + strictfp → ❌ Not allowed
Reason:
- Abstract methods have no implementation, but native methods already have implementation.
- Strictfp requires IEEE 754 compliance, which native languages may not follow.
Advantages
- the main advantage of native keywords is performance will be improved.
Disadvantages
- the main disadvantage of native keyword is it breaks the platform's independent nature in Java.
When the Java native method setTheString(), defined in the Java code, is called by the Java code the C function Java_NativeHello_setTheString() gets control and uses Java Native Interface (JNI) to call back into the Java code to set the value of the Java string variable theString. Control is then returned to the Java code, and the string variable is written to stdout out by the Java code.
JNI Example
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));
}
}
#include <jni.h>
#include "Main.h"
JNIEXPORT jint JNICALL Java_Main_intMethod
(JNIEnv *env, jobject obj, jint i) {
return i * i;
}
Compile & Run
javac Main.java
javah -jni Main
gcc -shared -fpic -o libMain.so -I${JAVA_HOME}/include \
-I${JAVA_HOME}/include/linux Main.c
java -Djava.library.path=. Main
0 Comments
Hello