HelloWorld.java
class HelloWorld { public native void helloWorld(); static { System.loadLibrary("nativelib"); } public static void main(String[] args) { HelloWorld h = new HelloWorld(); h.helloWorld(); } }
Compile the Program
javac HelloWorld.java
Generate the Header File
javah HelloWorld
HelloWorld.h
/* DO NOT EDIT THIS FILE - it is machine generated */ #include <jni.h> /* Header for class HelloWorld */ #ifndef _Included_HelloWorld #define _Included_HelloWorld #ifdef __cplusplus extern "C" { #endif /* * Class: HelloWorld * Method: helloWorld * Signature: ()V */ JNIEXPORT void JNICALL Java_HelloWorld_helloWorld (JNIEnv *, jobject); #ifdef __cplusplus } #endif #endif
HelloWorld.cpp
#include <iostream> #include "HelloWorld.h" using namespace std; JNIEXPORT void JNICALL Java_HelloWorld_helloWorld (JNIEnv *env, jobject o) { cout << "Hello World!" << endl; }
Compile the Library
g++ -Wall -shared -I/usr/java/jdk1.5.0_22/include -I/usr/java/jdk1.5.0_22/include/linux HelloWorld.cpp -o libnativelib.so
Run the Example
java -Djava.library.path=. HelloWorld
