5.13. Native Methods

It is possible to include in a class a method that is implemented in some other programming language, such as C or C++, external to the Java Virtual Machine. To specify such a method within a class definition, you use the keyword native in the declaration of the method. For example:

public native long getData();     // Declare a method that is not in Java

Of course, the method will have no body in Java since it is defined elsewhere, where all the work is done, so the declaration ends with a semicolon. The implementation of a native method will need to use an interface to the Java environment. The standard API for implementing native methods in C, for example, is called JNI—the Java Native Interface.

The major drawback to using native methods in Java is that your program will no longer be portable. Security requirements for applets embedded in web pages require that the code must all be written in Java-using native methods in an applet is simply not possible. Since the primary reasons for using Java are the portability of the code and the ability to produce applets, the need for you to add native methods to your Java programs will be minimal. I will therefore not delve any deeper into this topic.

Get Ivor Horton's Beginning Java™ 2, JDK™ 5th Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.