JNI short tutorial

Create a Java class to use code in C

1 Write a Java class that uses C codes

CraftJNI.java
public class CraftJNI {
  static {
    System.loadLibrary("hello"); // Load native library hello.dll (windows)
                                 // or libhello.so (Unixes) at runtime.
                                 // This library contains a native method sayHello()
                                 
  }
  
  // Declare an instance native method sayHello() which receives no parameter
  // returns void
  private native void sayHello();
  
  // Test Driver
  public static void main(String[] args) {
    new CraftJNI().sayHello(); // Create an instance and invoke native method
  }
}

2 Compile Java program CraftJNI.java

To know more about the generated class file

3 Implement C program

4 Compile C program

Troubleshooting

Error 1: class file has wrong version

Reason: javah is not available with Java 11

Error 2:

References

Last updated

Was this helpful?