How to use 'Native' in Java?

Asked

Viewed 77 times

1

In Java we have the keyword native. This keyword allows Java to delegate its execution to C and/or C++ allowing it to do certain things it is not able to.

Whereas I know the concepts of C and C++, how I use this keyword?

1 answer

1


First, let’s understand what it is Native in Java.

Simply put, your definition is correct, this is a access modifier used to access methods implemented in a language other than Java such as C / C ++

This functionality indicates the platform-dependent implementation of a method or code and also acts as an interface between [JNI][1] and other programming languages.

The following is an illustrative example:

  • Create a helloworld.java file
class HelloWorld
    {
    public native void printText ();
    static
   {
   System.loadLibrary ("helloworld");
   }
    public static void main (String[] args)
   {
   HelloWorld helloworld = new HelloWorld ();
   helloworld.printText ();
   }
    }
  • Compile

    % javac helloworld.java

Functionality boar of the Java compiler will generate the necessary and other declarations of our Helloworld class. This will create a Helloworld file. h to include in code C:

% javah HelloWorld

To alleviate the need to write tedious code so that C code can be called on the system at Java runtime, the Java compiler can automatically generate the necessary code:

% javah -stubs HelloWorld

Now, just write the real code to print say hi to the world. By convention, we should put the code in a file with the name of the Java class with the string "Imp" attached to it. This results in Helloworldimp. c. Put the following on Helloworldimp. c:

#include &ltStubPreamble.h>      
#include "HelloWorld.h"         
#include &ltstdio.h>         
void HelloWorld_printText (struct HHelloWorld *this)
    {
    puts ("Hello World!!!");
}

Then Compile the C source files you created. You must tell the compiler where to find the Java native method support files:

% gcc -I/usr/local/java/include -I/usr/local/java/include/genunix -fPIC -c HelloWorld.c HelloWorldImp.c

Now, create a shared library from the resulting object files (.o) with the following command:

% gcc -shared -Wl,-soname,libhelloworld.so.1 -o libhelloworld.so.1.0 HelloWorld.o HelloWorld.o

Copy the shared library file to the default abbreviated name:

% cp libhelloworld.so.1.0 libhelloworld.so

Finally, if you use Linux:

% export LD_LIBRARY_PATH=`pwd`:$LD_LIBRARY_PATH

Now just run it:

% java HelloWorld

To go beyond:

https://homepages.dcc.ufmg.br/~bigonha/Courses/Ap/Native/Javanativemethod.html ftp://ftp.inf.puc-rio.br/pub/docs/techreports/02_03_carasso.pdf

Browser other questions tagged

You are not signed in. Login or sign up in order to post.