// Assumption: I assume that you have already installed Java SDK on your machine and you are using Linux.
-
Open a Terminal
-
Open your favourite text editor, create a new file and write the following code
1 package com.sangeethlabs; 2 3 public class HelloJNI { 4 static { 5 System.loadLibrary("HelloJNI"); 6 } 7 public static native void greet(String message); 8 public static void main(String [] args) { 9 greet("Hello World !"); 10 } 11 }
Save the file as
HelloJNI.java
undercom/sangeethlabs
directory.
// NOTE: Ensure that the class name and the file name are same. -
Go back to your Terminal
-
run the following command to compile the source code:
javac com/sangeethlabs/HelloJNI.java
This generates a class file named
HelloJNI.class
in the same directory. -
Now run the following command to generate header file for native code.
javah com.sangeethlabs.HelloJNI
This results in a C/C++ header file named com_sangeethlabs_HelloJNI.h in the same directory with the following contents
/* DO NOT EDIT THIS FILE - it is machine generated */ #include <jni.h> /* Header for class com_sangeethlabs_HelloJNI */ #ifndef _Included_com_sangeethlabs_HelloJNI #define _Included_com_sangeethlabs_HelloJNI #ifdef __cplusplus extern "C" { #endif /* * Class: com_sangeethlabs_HelloJNI * Method: greet * Signature: (Ljava/lang/String;)V */ JNIEXPORT void JNICALL Java_com_sangeethlabs_HelloJNI_greet (JNIEnv *, jclass, jstring); #ifdef __cplusplus } #endif #endif
-
Open your favourite text editor, create a new file and write the following code
Save the file as HelloJNI.cpp.1 #include "com_sangeethlabs_HelloJNI.h" 2 3 #include <stdio.h> 4 5 JNIEXPORT void JNICALL Java_com_sangeethlabs_HelloJNI_greet 6 (JNIEnv *env, jclass jClazz, jstring jstrText) { 7 8 const char *str; 9 str = env->GetStringUTFChars(jstrText, NULL); 10 printf("%s\n", str); 11 env->ReleaseStringUTFChars(jstrText, str); 12 }
-
Now compile the C++ code and create a shared object named libHelloJNI.so using the following commands
g++ -shared -I$JAVA_HOME/include/ -I$JAVA_HOME/include/linux -fPIC -g -c HelloJNI.cpp g++ -shared -Wl,-soname,libHelloJNI.so -o libHelloJNI.so -lc HelloJNI.o
-
Now run the following command to execute the Java class.
java -cp . -Djava.library.path=. com.sangeethlabs.HelloJNI
The output of the program will be as shown below,
Hello World !
// NOTE: “-Djava.library.path=.” option indicates to JVM that “libHelloJNI.so” can be located under the current directory. Another alternative is to set the environment variable LD_LIBRARY_PATH to include the path under which “libHelloJNI.so” can be located. By doing so, we can execute the Java code as shown below
export LD_LIBRARY_PATH=.:$LD_LIBRARY_PATH java -cp . com.sangeethlabs.HelloJNI
Now you have successfully executed your first Java program using Java Native Interface on Linux !