Specify the native keyword in Java

  • 2020-05-05 11:12:12
  • OfStack

  i. what is Native Method
Simply put, an Native Method is an java interface that calls non-java code. An Native Method is an java method whose implementation is implemented in a non-java language, such as C. This feature is not unique to java. Many other programming languages have this mechanism. For example, in C++, you can tell the C++ compiler to call an C function with extern "C".
    "A native method is a Java method whose implementation is provided by non-java code."
    does not provide an implementation body (some like defining an java interface) when it defines an native method, because the implementation body is implemented externally by non-java languages. Here is an example:    


package java.lang; 
public class Object { 
  ......
  public final native Class<?> getClass(); 
  public native int hashCode(); 
  protected native Object clone() throws CloneNotSupportedException; 
  public final native void notify(); 
  public final native void notifyAll(); 
  public final native void wait(long timeout) throws InterruptedException; 
  ......
} 

The identifier native can be used with all other java identifiers, except abstract. This makes sense, because native implies that these methods have implementors that are not java, while abstract clearly indicates that these methods have no implementors. When native is used with other java identifiers, its meaning is no different from that of non-Native Method.

An native method method can return any java type, including non-basic types, and can also be used for exception control. Implementations of these methods can make an exception and throw it, much like java's method.

The presence of native method does not have any effect on other classes calling these local methods, and in fact the other classes calling these methods do not even know that it is calling a local method. JVM will control all the details of calling local methods.

If a class with a local method is inherited, the subclass inherits the local method and can override the method in java language (this seems odd). Likewise, if a local method is identified by fianl, it cannot be overridden after inheritance.

The local method is useful because it effectively extends jvm. In fact, the java code we wrote already USES local methods, and in sun's concurrent (multithreaded) java implementation, many of the points of contact with the operating system use local methods, allowing java programs to transcend java runtime boundaries. With local methods, the java program can do any application-level task.

ii. Method of use

The native keyword states that the method it modifies is a primitive method that corresponds to an implementation not in the current file but in a file implemented in other languages such as C and C++. The Java language itself cannot access and manipulate the underlying operating system, but it can be accessed by calling other languages through the JNI interface.

JNI is the Java native interface (Java Native Interface), a native programming interface that is part of the Java software development toolkit (Java Software Development Kit, SDK). JNI allows Java code to use code and code bases written in other languages. Invocation API (part of JNI) can be used to embed Java virtual machines (JVM) into native applications, allowing programmers to call Java code from within native code.

However, calls to the outside of Java are generally not portable to other platforms, and security exceptions can be thrown in applet. Implementing native code will prevent your Java application from passing the 100% Java test. However, if you must make a local call, consider a few guidelines:

1. Encapsulate all your local methods into a class that invokes a single DLL. For each target operating system platform, the appropriate platform-specific version of DLL can be used. This minimizes the impact of native code and helps to take into account future migration needs.

2. Keep local methods simple. Try to minimize the dependency of your local methods on the DLL runtime of third parties (including Microsoft). Keep your local methods as independent as possible to minimize the overhead of loading your DLL and applications. If the runtime DLL is required, it must be provided with the application.

The steps to write JNI are as follows:

a. b. Java c d. Use other languages (C, C++) to implement the local method e

Here is a simple example of calling a local C program in Java:

a. HelloWorld.java class


class HelloWorld{

public native void hello();

static{
System.loadLibrary("hello");
}

public static void main(String[] args){

new HelloWorld().hello();
}

}

b. Compile

javac HelloWorld.java

c. Generate.h file

javah -jni HelloWorld

The generated content is as follows:


/* 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: hello
* Signature: ()V
*/
JNIEXPORT void JNICALL Java_HelloWorld_hello
(JNIEnv *, jobject);

#ifdef __cplusplus
}
#endif
#endif

The first parameter is the JNI Environment pointer used when calling the JNI method. The second parameter is a handle to Java object HelloWorld that is instantiated in this Java code. The other arguments are

for the method itself

d.c implements


#include <jni.h>
#include "HelloWorld.h"
#include <stdio.h>
JNIEXPORT void JNICALL Java_HelloWorld_hello(JNIEnv *env,jobject obj){
printf("Hello World!\n");
return;
}

The first line introduces the jni.h file (in the directory %JAVA_HOME%\include) with the definitions for JNIEnv and jobject.

e. Compile c to implement

For example, in Windows, you need to generate the dll file. Under the HelloWorldImpl.c folder, use the compiler cl for VC.

cl -I%java_home%\include -I%java_home%\include\win32 -LD HelloWorldImp.c -Fehello.dll

Note: the generated dll file name is configured after the option -Fe, which is hello, because we used the name loadLibary in HelloWorld.java. Of course, after the changes here, we need to change there. In addition, the -I %java_home%\ include-I %java_home%\include\win32 parameter needs to be added, because the jni.h file was introduced when the local method was written in step 4.

f. Run

java HelloWorld is ok!

The above is the detailed introduction of native keyword in Java. I hope it will be helpful to you.