The JavaTM Tutorial
Previous Page Lesson Contents Next Page Start of Tutorial > Start of Trail > Start of Lesson Search
Feedback Form

Trail: Java Native Interface
Lesson: Writing a Java Program with Native Methods

Step 4: Write the Native Method Implementation

Now, you can finally write the implementation for the native method in a language other than Java.

Note:  Back to that "real world," C and C++ programmers may already have existing implementations of native methods. For those "real" methods, you need only ensure that the native method signature matches the signature generated on the Java side.

The function that you write must have the same function signature as the one generated by javah in the HelloWorld.h file in Step 3: Create the .h File. Recall that the function signature generated for the HelloWorld class's displayHelloWorld native method looks like this:

JNIEXPORT void JNICALL
    Java_HelloWorld_displayHelloWorld(JNIEnv *, jobject);
Here's the C language implementation for the native method Java_HelloWorld_displayHelloWorld. This implementation is in the file named HelloWorldImp.c.
#include <jni.h>
#include "HelloWorld.h"
#include <stdio.h>

JNIEXPORT void JNICALL 
Java_HelloWorld_displayHelloWorld(JNIEnv *env, jobject obj) 
{
    printf("Hello world!\n");
    return;
}
The implementation for Java_HelloWorld_displayHelloWorld is straightforward. The function uses the printf function to display the string "Hello World!" and then returns.

The HelloWorldImp.c file includes three header files:

  1. jni.h - This header file provides information that the native language code requires to interact with the Java runtime system. When writing native methods, you must always include this file in your native language source files.
  2. HelloWorld.h - The .h file that you generated in Step 3: Create the .h File.
  3. stdio.h - The code snippet above includes stdio.h because it uses the printf function. The printf function is part of the stdio.h library.

Previous Page Lesson Contents Next Page Start of Tutorial > Start of Trail > Start of Lesson Search
Feedback Form

Copyright 1995-2002 Sun Microsystems, Inc. All rights reserved.