First, what is Java native method?
"A native method is a Java method whose implementation was provided by Non-java code."
In a nutshell, native method is the interface that Java calls non-Java code, the implementation of which is implemented by non-Java code, such as C, C + +.
Defining a native Method does not provide a specific implementation body (a bit like Java Interface), because its implementation is non-Java code implemented outside.
Public class Itestnativemethod { nativepublicvoid native (int x); native Static Public Long Native (); native synchronized Private float Native (Object o); }
The declaration of these methods describes what the non-Java code looks like in Java code.
A native method can return any Java type, including non-basic types, and can be controlled with exception. The implementations of these methods can make an exception and throw the exception.
Second, why use native Method?
Java is easy to use, but some aspects of the task are not easy to implement in Java.
1, with the Java Environment Diplomacy Mutual:
Sometimes Java applications need to interact with environments outside of Java. such as Java needs to interact with the underlying system.
2. Interacting with the operating system
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.
Third, how the JVM makes native method run up
We know that when a class is used for the first time, the bytecode of this class is loaded into memory and is loaded only once. At the entrance of the loaded bytecode is a list of all the method descriptors for that class, and the descriptors of these methods contain information such as where the method code is stored, what parameters it has, how it is
Descriptor (public/private/proected), and so on.
If a method has native in the contempt, 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 it points to the method implemented by the
The pointer is not set. These DLLs are not loaded until the local method is called, which is implemented by calling Java.system.loadLibrary ().
Java Native Method