javah and headers
- Java course
- Expert
- Lesson 26/46
- 5 min
Learn to generate headers with javac -h.
Header generation with javac -h
The old javah tool generated C header files for native methods; it is deprecated since Java 8. Instead use javac -h . Class.java. This compiles the class and writes Class.h into the same folder.
The header file contains a C function declaration for each native method: JNIEXPORT jint JNICALL Java_NativeOps_sum(JNIEnv*, jclass, jint, jint);. You implement these functions on the C side.
Contents of the header file
The generated .h file carries a C function declaration for each native method. The declaration looks like: JNIEXPORT returnType JNICALL Java_Class_method(JNIEnv* env, jclass cls, ...). JNIEXPORT marks export, JNICALL is the calling convention and JNIEnv* lets C reach the JVM.
For non-static methods the second parameter is jobject (this); for static methods it is jclass. You implement these functions in C and compile them into a shared library.
Practice Declare two native methods and print a header marker
Define class NativeOps with native int sum(int a, int b); and native String greet(String name);. In Main's main method print System.out.println("header generated");. Do not call the methods.
Starter code
// Define the NativeOps class: native int sum and native String greet
// Define the Main class and print header generated in mainSample solution
class NativeOps {
native int sum(int a, int b);
native String greet(String name);
}
public class Main {
public static void main(String[] args) {
System.out.println("header generated");
}
}Expected output
header generated
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Complete the header-generating command
javac ____ NativeOps.java
javac -h . NativeOps.java
Explanation: The command javac -h . NativeOps.java generates the header.
2 What does javac -h produce?
- An executable JAR
- Documentation HTML
- A C header file (.h) Correct answer
- A class file (.class)
Explanation: javac -h produces a C header file for the native methods.
3 Match the header elements
| Term | Meaning |
|---|---|
JNIEXPORT |
Export macro |
JNICALL |
Calling convention |
JNIEnv* |
C interface pointer |
jclass |
Class reference |