Java native keyword example
- Details
- Written by Nam Ha Minh
- Last Updated on 19 August 2019   |   Print Email
In Java, the native keyword is used to declare a method which is implemented in platform-dependent code such as C or C++. When a method is marked as native, it cannot have a body and must ends with a semicolon instead. The Java Native Interface (JNI) specification governs rules and guidelines for implementing native methods, such as data type conversion between Java and the native application.
The following example shows a class with a method declared as native:
public class NativeExample { public native void fastCopyFile(String sourceFile, String destFile); }
See all keywords in Java.
Other Recommended Tutorials:
- 9 Rules about Constructors in Java
- 12 Rules and Examples About Inheritance in Java
- 12 Rules of Overriding in Java You Should Know
- 10 Java Core Best Practices Every Java Programmer Should Know
- Understand Interfaces in Java
- Understand how variables are passed in Java
- Understand encapsulation in Java
Comments
Compile and run:
javac Main.java -h .
gcc -dynamiclib -O3 \
-I/usr/include \
-I$JAVA_HOME/include \
-I$JAVA_HOME/include/darwin \
Main.c -o libMain.dylib
java -cp . -Djava.library.path=$(pwd) Main
Output:
4
as well as yours truly :). Keep doing what you are
doing - looking forward to more posts.
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
#include "Main.h"
JNIEXPORT jint JNICALL Java_Main_intMethod(
JNIEnv *env, jobject obj, jint i) {
return i * i;
}
Compile and 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
Output:
4