Java – JNI CALL changes jclass parameters or how to get jobject from jclass parameters

JNI CALL changes jclass parameters or how to get jobject from jclass parameters… here is a solution to the problem.

JNI CALL changes jclass parameters or how to get jobject from jclass parameters

I’m testing some features using Android, JNI, and NDK.

I HAVE THE FOLLOWING JAVA CLASS:

import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.TextView;

public class JNITest extends Activity {
    private int contador;
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

contador = 0;
        TextView label = (TextView)findViewById(R.id.Text);
        label.setText(Integer.toString(contador));
    }

public void addClick(View addButton) {
        nativeAdd(1);
        TextView label = (TextView)findViewById(R.id.Text);
        label.setText(Integer.toString(contador));
    }

private static native void nativeAdd(int value);

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

I’ve generated the header file with javah -jni:

#include <jni.h>
/* Header for class es_xxxxx_pruebas_JNITest */

#ifndef _JNITestNative
#define _JNITestNative
#ifdef __cplusplus
extern "C" {
#endif
/*
 * Class:     com_xxxxx_tests_JNITest
 * Method:    nativeAdd
 * Signature: (I)V
 */
JNIEXPORT void JNICALL Java_com_xxxxx_tests_JNITest_nativeAdd
(JNIEnv *, jclass, jint);

#ifdef __cplusplus
}
#endif
#endif

As you can see, the second parameter is the jclass type.

I would like to know how to change jclass for jobject parameter.

I need a jobject parameter to get the value from the field of the class that calls this native function.

How do I change the method signature? Or how to get jobject from jclass parameter?

Thank you.

Solution

Static methods do not have access to the object (implicitly this parameter), only other static methods/properties of the class. That’s why your native method has jclass instead of jobject.

So, change your Java method to a non-static method and regenerate your header file.

By the way, you

can create Java objects from JNI, but in this case I think you want to be able to change the value of the member variable contador so that doesn’t help you.

Related Problems and Solutions