1. What is Native Method
Simply put, a Native Method is an interface in which java calls non-java code. A Native Method is a Java method: the implementation of this method is implemented by 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 use extern "C" to tell the C++ compiler to call a C function.
"A native method is a Java method whose implementation is provided by non-java code."
When defining a native method, the implementation body is not provided (some are like defining a java interface), because its implementation body is implemented outside by a non-java language. , 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; ......}Identifier native can be used with all other java identifiers, except abstract. This is reasonable because native implies that these methods have implementation bodies, but these implementation bodies are non-java, but abstract obviously indicates that these methods have no implementation bodies. When native and other java identifiers are used, their meaning is no different from that of non-Native Methods.
A native method method can return any java type, including non-primitive types, and can also perform exception control. The implementation of these methods can make an exception and throw it, which is very similar to Java's method.
The existence of native method does not have any effect on other classes calling these local methods. In fact, other classes that call these methods don't even know that it is calling a local method. The JVM will control all the details of calling the local method.
If a class containing a local method is inherited, the subclass will inherit the local method and can rewrite the method in Java (this seems a bit strange). Similarly, if a local method is identified by fianl, it cannot be rewrite after it is inherited.
Local methods are very useful because they effectively expand jvm. In fact, the java code we write has used local methods. In the implementation of sun's java concurrency (multi-threading) mechanism, many contact points with the operating system use local methods, which enables java programs to exceed the boundaries of java runtime. With local methods, Java programs can do any application-level tasks.
2. How to use
The native keyword indicates that its modification method is an original method. The corresponding implementation of the method is not in the current file, but in files implemented in other languages (such as C and C++). The Java language itself cannot access and operate the underlying layer of the operating system, but it can use the JNI interface to call other languages to achieve access to the underlying layer.
JNI is a Java Native Interface, a native programming interface, which is part of the Java Software Development Kit (SDK). JNI allows Java code to use code and code bases written in other languages. The Invocation API (part of JNI) can be used to embed Java virtual machines (JVMs) into native applications, allowing programmers to call Java code from inside native code.
However, calls to external Java cannot usually be ported to other platforms, and security exceptions may also be raised in applets. Implementing native code will prevent your Java application from passing 100% pure Java testing. However, if a local call must be performed, there are several guidelines to consider:
1. Encapsulate all your local methods into a class that calls a single DLL. For each target operating system platform, a version of the DLL specific to the appropriate platform can be used. This minimizes the impact of the local code and helps take into account the required porting issues later.
2. The local method is as simple as possible. Try to minimize your local method's dependence on third-party (including Microsoft) runtime DLLs. Make your local method as independent as possible to minimize the overhead required to load your DLL and application. If a runtime DLL is required, it must be provided with the application.
The writing steps of JNI are as follows:
Here is a simple example of calling a local C program in Java:
a. Write HelloWorld.java class
class HelloWorld{public native void hello();static{System.loadLibrary("hello");}public static void main(String[] args){new HelloWorld().hello();}}b. Translation
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 __cplusplusextern "C" {#endif/** Class: HelloWorld* Method: hello* Signature: ()V*/JNIEXPORT void JNICALL Java_HelloWorld_hello(JNIEnv *, jobject);#ifdef __cplusplus}#endif#endifThe first parameter is the JNI Environment pointer used when calling the JNI method. The second parameter is a handle to the Java object HelloWorld instantiated in this Java code. Other parameters are parameters of the method itself
dc implementation
#include <jni.h>#include "HelloWorld.h"#include <stdio.h>JNIEXPORT void JNICALL Java_HelloWorld_hello(JNIEnv *env,jobject obj){printf("Hello World!/n");return;}Among them, the first line is to introduce the jni.h file (in the %JAVA_HOME%/include directory), which contains the definitions of JNIEnv and jobject.
e. Compile c implementation
Here, taking Windows as an example, you need to generate a dll file. Under the save HelloWorldImpl.c folder, use the VC compiler to create it.
cl -I%java_home%/include -I%java_home%/include/win32 -LD HelloWorldImp.c -Fehello.dll
Note: The generated dll file name is configured after option -Fe, here is hello, because the name we use when loadLibary in HelloWorld.java file is hello. Of course, after modification here, it also needs to be modified there. In addition, the -I%java_home%/include -I%java_home%/include/win32 parameter needs to be added, because the jni.h file is introduced when writing the local method in the fourth step.
f. Run the program
java HelloWorld is OK!
The above is a detailed introduction to native keywords in Java, and I hope it will be helpful to everyone's learning.