native keyword

Syntax

>>-+-----------+-+--------+-+-------+-+--------------+->
   +-public----+ '-static-' '-final-' '-synchronized-'
   +-protected-+
   '-private---'

>-native-ResultType-Identifier-(-+---------------------+-)->
                                 '-FormalParameterList-'

>-+----------------------+-;-><
  '-throws-ClassTypeList-'

Description
A method that is native is implemented in platform-dependent code, typically written in another programming language such as C, C++, FORTRAN, or assembly language. The body of a native method is given as a semicolon only, instead of a block, indicating that the implementation is omitted.

If a native method is declared abstract, a compilation error occurs.

Note that a method declared in an interface must not be declared native or a compilation error occurs, because native describes implementation properties rather than interface properties. However, a method declared in an interface may be implemented by a method that is declared native in a class that implements the interface. Unlike methods, a constructor cannot be declared native.

If native methods are to be used in the implementation of a class, a standard strategy is to put the native code in a library file (called, for example, LibFile) and then to put a static initializer:

static { System.loadLibrary("LibFile"); }

within the class declaration. When the class is loaded and initialized, the necessary native code implementation for the native methods will then be loaded as well.

Example
The class RandomAccessFile of the standard package java.io might declare the following native methods:

package java.io;
public class RandomAccessFile implements DataOutput, DataInput
{   . . .
    public native void open(String name, boolean writeable)throws IOException;
    public native int readBytes(byte[] b, int off, int len)throws IOException;
    public native void writeBytes(byte[] b, int off, int len)throws IOException;
    public native long getFilePointer() throws IOException;
    public native void seek(long pos) throws IOException;
    public native long length() throws IOException;
    public native void close() throws IOException;
}

ngrelr.gif (548 bytes)
Syntax diagrams
Class constructors
abstract keyword
class keyword
final keyword
private keyword
protected keyword
public keyword
static keyword
synchronized keyword

Source: The Java Language Specification. Copyright (C) 1996 Sun Microsystems, Inc.