How to call a Java method from native code

suggest change

The Java Native Interface (JNI) allows you to call Java functions from native code. Here is a simple example of how to do it:

Java code:

package com.example.jniexample;
public class JNITest {
    public static int getAnswer(bool) {
        return 42;
    }
}

Native code:

int getTheAnswer()
{
    // Get JNI environment
    JNIEnv *env = JniGetEnv();

    // Find the Java class - provide package ('.' replaced to '/') and class name
    jclass jniTestClass = env->FindClass("com/example/jniexample/JNITest");

    // Find the Java method - provide parameters inside () and return value (see table below for an explanation of how to encode them) 
    jmethodID getAnswerMethod = env->GetStaticMethodID(jniTestClass, "getAnswer", "(Z)I;");

    // Calling the method
    return (int)env->CallStaticObjectMethod(jniTestClass, getAnswerMethod, (jboolean)true);
}

JNI method signature to Java type:

| JNI Signature | Java Type | | —— | —— | |Z|boolean| |B|byte| |C|char| |S|short| |I|int| |J|long| |F|float| |D|double| |L fully-qualified-class ;|fully-qualified-class| |[ type|type[]|

So for our example we used (Z)I - which means the function gets a boolean and returns an int.

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents