The role of the Native keyword in Java, the javanative keyword

Source: Internet
Author: User

The role of the Native keyword in Java, the javanative keyword

The first time I met native, It Was A hashCode method in the java. lang. Object source code:

1 public native int hashCode();

Why is there a native? This is what I want to learn. Therefore, we would like to summarize native below.

1. Understand native, namely JNI and Java Native Interface

All languages must be pure. For example, a solution can be written in this language alone. The Java platform has an API that allows users to interoperate with local C code. It is called Java Native Interface (Java Local Interface ).

 

2. Use Java to call C's "Hello, JNI"

We need to follow the convenient steps after work:

1. Create a Java classContains a native method and the loadLibrary Method for loading the library. The HelloNative. java code is as follows:

123456789101112131415 public class HelloNative{    static    {        System.loadLibrary("HelloNative");    }         public static native void sayHello();         @SuppressWarnings("static-access")    public static void main(String[] args)    {        new HelloNative().sayHello();    }}

First, let everyone pay attention to the native method, which also takes effect after the library is loaded. The native keyword tells the compiler (actually the JVM) to call the method in an external definition. Here it refers to C. If you directly run this code, the JVM will tell you: "A Java Exception has occurred." The console output is as follows:

12345 Exception in thread "main" java.lang.UnsatisfiedLinkError: no HelloNative in java.library.path    at java.lang.ClassLoader.loadLibrary(Unknown Source)    at java.lang.Runtime.loadLibrary0(Unknown Source)    at java.lang.System.loadLibrary(Unknown Source)    at HelloNative.<clinit>(HelloNative.java:5)

When the program uses it, the virtual machine says it does not know how to find sayHello. Which of the following can be manually written?

2. Run javahTo obtain the C statement containing this method.Header file. h

Put HelloNative. java, javac javah,

You can see the followingHelloNative. h file:

123456789101112131415161718192021 /* DO NOT EDIT THIS FILE - it is machine generated */#include <jni.h>/* Header for class HelloNative */ #ifndef _Included_HelloNative#define _Included_HelloNative#ifdef __cplusplusextern "C" {#endif/* * Class:     HelloNative * Method:    sayHello * Signature: ()V */JNIEXPORT void JNICALL Java_HelloNative_sayHello  (JNIEnv *, jclass); #ifdef __cplusplus}#endif#endif

Jni. h file in/% JAVA_HOME % include

3. Write according to the header fileC implementation local method.

Here we can simply implement this sayHello method as follows:

1234567 #include "HelloNative.h"#include <stdio.h> JNIEXPORT void JNICALL Java_HelloNative_sayHello{    printf("Hello,JNI");    }

4. Generate a dll shared library, And then the Java Program load Library,CallYou can.

On Windows, MinGW GCC runs as follows:

1 gcc -m64  -Wl,--add-stdcall-alias -I"C:\Program Files\Java\jdk1.7.0_71\include" -I"C:\Program Files\Java\jdk1.7.0_71\include\include\win32" -shared -o HelloNative.dll HelloNative.c

-M64 indicates that the dll library is generated 64-bit. Then runHelloNative:

1 java HelloNative

 

Finally, the console is displayed as follows:

1 Hello,JNI
Iii. flowchart of JNI Calling C

4. Other introductions

Native is used for joint development with C ++! Java development is not required!


The native keyword indicates that this method is a native function, that is, this method is implemented in C/C ++ and compiled into a DLL, which is called by java.
The implementation of these functions is in the DLL, And the JDK Source Code does not contain them. You should not see them. They are also different for different platforms. This is also the underlying mechanism of java. In fact, java calls different native methods on different platforms to access the operating system.


1. Native is used for java and other languages (such as c ++) for collaboration.
That is, the implementation of native functions is not written in java.
2. Since it is not java, don't worry about its source code.


Native means to notify the operating system,
You must implement this function for me because I want to use it.
Therefore, functions with native keywords are implemented by the operating system,
Java can only be called.


Java is a cross-platform language. Since it is a cross-platform language, the cost is to sacrifice some control over the underlying layer, while java must implement control over the underlying layer, we need help from other languages. This is the role of native.

Java is not perfect. In addition to its shortcomings, Java is much slower than traditional C ++ in terms of running speed. In addition, Java cannot directly access the underlying operating system (such as system hardware ), therefore, Java uses the native method to extend the functions of Java programs.
The native method can be compared to the interface of a Java program and a C program. The implementation steps are as follows:
1. Declare the native () method in Java and compile it;
2. Use javah to generate a. h file;
3. Write a. cpp file to implement the native export method, which must contain the. h file generated in step 2 (note that it contains the jni. h file in JDK );
4. Compile the. cpp file in step 3 into a dynamic link library file;
5. Use the System. loadLibrary () method in Java to load the dynamic link library file generated in Step 4. This native () method can be accessed in Java.


JAVA local method
1. To use a feature of the underlying host platform, this feature cannot be accessed through JAVA APIs.

2. to access an old system or use an existing library, this system or library is not written in JAVA.

3. to speed up the performance of the program, use sensitive code for a period of time as a local method.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.