Java Native Interface(JNI)

By Ajay Shankar Maurya March 8, 2018

Writing functionality from the most beginning in order to modify existing functionality of applications is not an easy task as well as superfluous. So at the most extent, it would be a great idea to use native codes, which has already written in different languages. which also motivates for code reusability.

In Java, JNI (Java Native Interface)is the way to do so.Suppose there is a scenario where Java doesn’t support platform-specific features or it is difficult to write an entire application in java language for a particular platform, So to handle these situation programmers are able to use JNI.

Followings are the points to be considered for using JNI:

-> As we are using existing codes, which motivates for code reusability.

-> We can call Java objects from other languages (C, C++), same as called by java.

-> Native methods are not interpreted by JVM, nor method be compiled, thus natives codes are much faster than Java code when running in interpreted mode.

-> Also our program is no longer platform independent.

-> We can throw and catch exceptions from native methods also.

Implementation

Followings are the steps to use native methods :

1. Write a class that will use the native methods (Translator.java).

2. Compile created class (javac Translator),a ‘Translator.class’ will be generated.

3. After that by using ‘javah -jni Translator’ JVM will generate a C header file (Translator.h) which contains the native method.

4. As we are using the native method so it must be already implemented.

5. We will write ‘CLibTranslator.c’ which contains that native method.

6. Compiling of above c implementation into a native library will result in Translator.dll.

7. Finally, we will run our java program.

Step 1 – Create Transslator.java

class Translator {

public native void input(); // Native method
static    //Native library should be initialized as static
{
System.loadLibrary(“CLibTranslator”);
}
public static void main(String[] args)
{
Translator translator = new Translator();
translator.input();
}
}

Step 2 – Generate header file.

javah -jni Translator

Output:

/* DO NOT EDIT THIS FILE – it is machine generated */

#include

/* Header for class Translator */

#ifndef _Included_HelloWorld

#define _Included_HelloWorld

#ifdef __cplusplus

extern “C” {

#endif

/*

* Class:     Translator

* Method:    input

* Signature: ()V

*/

JNIEXPORT void JNICALL Java_Transslator_input

(JNIEnv *, jobject);

#ifdef __cplusplus

}

#endif

#endif

Step 3 – Writing the C implementation

#include “Translator.h”

#include “jni.h”

#include “stdio.h”

JNIEXPORT void JNICALL Java_Translator_input(JNIEnv *env, jobject obj)

{

printf(“I’m from anothespace”);

return;

}

Step 4 – Running java

java Translator

Output

I’m from anotherspace

Our Latest Blog

Read Through our Blog