I. What is native Method
In a nutshell, a native method is a Java interface that calls non-Java code. A native method is a Java approach: the implementation of this method is implemented by non-Java languages, such as C. This feature is not specific to Java, many other programming languages have this mechanism, such as in C + +, you can use the extern "C" to tell the C + + compiler to call a C function.
"A native method is a Java method whose implementation was provided by Non-java code."
When defining a native method, the implementation body is not provided (some like the definition of a Java interface) because its implementation is implemented outside the non-Java language.
The native keyword indicates that its modification is a primitive method, and the corresponding implementation of the method is 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 other languages can be invoked through the JNI interface to enable access to the underlying
JNI is a Java Native interface (Java Native Interface) and is 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 libraries written in other languages. The invocation API (part of the JNI) can be used to embed a Java Virtual machine (JVM) into a native application, allowing programmers to invoke Java code from within native code.
However, calls outside of Java are often not ported to other platforms, and security exceptions can be thrown in applets. Implementing native code will make your Java application fail to pass 100% pure Java testing.
However, there are several guidelines to consider if you must perform a local call:
1. Encapsulate all your local methods into a class that calls a single DLL. For each target operating system platform, you can use a DLL that is specific to the appropriate platform version. This minimizes the impact of native code and helps to take into account the migration issues that are needed later. 2. The local method is as simple as possible. Try to minimize the reliance of your local methods on third-party (including Microsoft) run-time DLLs. Keep your local methods as independent as possible to minimize the overhead required to load your DLLs and applications. If a runtime DLL is required, it must be supplied with the application.
An example is given below:
PackageJava.lang; Public classObject {... Public Final nativeClass<?>getclass (); Public native inthashcode (); protected nativeObject Clone ()throwsclonenotsupportedexception; Public Final native voidnotify (); Public Final native voidNotifyall (); Public Final native voidWaitLongTimeoutthrowsinterruptedexception; ......}
The identifier native can be used with all other Java identifiers, except for abstract. This is justified because native implies that these methods are implemented, except that the implementations are non-Java, but the abstract clearly indicates that these methods are not implemented. Native and other Java identity Connect prompt time, its meaning and non-native method is not different.
A native method can return any Java type, including non-basic types, and can also be used for exception control. The implementation of these methods can make an exception and throw it, which is very similar to the Java approach.
The presence of the native method does not have any effect on other classes calling these local methods, and the other classes that actually call these methods do not even know that it is calling a local method. The JVM controls all the details of calling the local method.
If a class with a local method is inherited, the subclass inherits the local method and can rewrite the method in the Java language (this may seem strange), as well if a local method is fianl identified, it cannot be overridden after it is inherited.
Local methods are very useful, Because it effectively expands the JVM. In fact, the Java code we write has already used native methods, and in the implementation of the Concurrency (multithreading) mechanism of Sun's Java, many of the contact points of the operating system have been used locally, which allows the Java program to go beyond the Java runtime boundaries. With local methods, Java programs can do any application-level tasks.
Two. Why use native Method
Java is very convenient to use, but some levels of tasks are not easy to implement in Java, or we are concerned about the efficiency of the program, the problem comes.
Diplomacy with the Java environment:
Sometimes Java applications need to interact with environments outside of Java. This is the main reason why the local method exists, and you can think about how Java needs to exchange information with some underlying systems, such as the operating system or some hardware. The local approach is one such communication mechanism: it provides us with a very concise interface, and we do not need to understand the tedious details outside of Java applications.
Interacting with the operating system:
The JVM supports the Java language itself and the runtime library, which is the platform on which the Java program survives, consisting of an interpreter (the explanatory bytecode) and some libraries connected to the local code. However, after all, it is not a complete system, it often relies on some of the underlying (underneath) system support. These underlying systems are often powerful operating systems. By using the native method, we were able to implement the JRE's interaction with the underlying system in Java, and even some parts of the JVM were written in C, and if we were to use some of the Java language itself without providing the features of the encapsulated operating system, we would also need to use local methods.
Sun ' s Java
Sun's interpreter is implemented in C, which allows it to interact with the outside like some normal C. Most of the JRE is implemented in Java, and it interacts with the outside world through some local methods. For example, the SetPriority () method of the class Java.lang.Thread is implemented in Java, but it implements the invocation of the Local Method SetPriority0 () in the class. This local method is implemented in C and is implanted inside the JVM, and on the Windows 95 platform, this local method will eventually invoke the Win32 setpriority () API. This is a specific implementation of a local method that is provided directly by the JVM, and more generally, the local method is provided by the external dynamic link library (external. dll) and then called by the JVM.
Three. How the JVM makes native method run:
We know that when a class is first used, the byte code of this class is loaded into memory and is only reloaded once. The entrance to the loaded bytecode maintains a list of all the method descriptors for that class, which contain information such as where the method code is stored, what parameters it has, the method's descriptor (public, and so on), and so on.
If there is a native in a method descriptor, this description converts sequential blocks will have a pointer to the implementation of the method. These implementations are within some DLL files, but they are loaded into the Java program's address space by the operating system. When a class with a local method is loaded, its associated DLL is not loaded, so pointers to the implementation of the method are not set. These DLLs are not loaded until the local method is called, which is implemented by calling Java.system.loadLibrary ().
The last thing to note is that the use of local methods is expensive, and it loses many of the benefits of Java. If there is no choice, we can choose to use local methods.
The native method can be likened to the Java program's interface to the C program, and its implementation steps:
1.declare the native () method in Java and compile (Java class written using the Javac command);2. UseJavah to produce an. h file (using JAVA-JNI * * * * to generate a header file with the suffix. h); 3, write a. cpp file to implement the native export method, which needs to include the second step produced by the. h file (Note that it also contains the JDK jni.h file) (in other languages (c, C + +) to implement the Local method);4, Compile the third step. cpp file into a dynamic-link library file (generate a dynamic-link library of files written by local methods);5. Load the dynamic link library file generated by the fourth step in Java using the System.loadlibrary () method, this native () Method can be accessed in Java.
The following is a simple example of calling a local C program in Java:
A. Writing the Helloworld.java class
class helloworld{ publicnativevoid hello (); Static { system.loadlibrary ("Hello"); } Public Static void Main (string[] args) { new HelloWorld (). hello (); } }
B. Compiling
Javac Helloworld.java
C. Generating the. h file
Javah-jni HelloWorld
The generated content is as follows:
/*Do not EDIT this file-it are 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*/Jniexportvoidjnicall Java_helloworld_hello (jnienv*, Jobject); #ifdef __cplusplus}#endif #endif
The first parameter is the JNI environment pointer used when invoking 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
D.C implementation
#include <jni.h> "HelloWorld.h" <stdio.h> void Jnicall Java_helloworld_hello (jnienv *env,jobject obj) { printf ("Hello world!\n "); return ; }
The first line is the introduction of the Jni.h file (in the%java_home%\include directory) with the definition of jnienv and jobject.
E. Compiling C implementations
Here, for example in Windows, you need to generate a DLL file. Under Save Helloworldimpl.c folder, use VC's compiler to CL.
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, here is hello, because in the Helloworld.java file we loadlibary used the name is hello. Of course there is a need to modify it after this change. It is also necessary to add the-i%java_home%\include-i%java_home%\include\win32 parameter because the jni.h file is introduced when writing the local method in step fourth.
F Running the program
It's OK!
Other view http://www.ibm.com/developerworks/cn/java/jnimthds/Learn more
Java keyword native