Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unable to refer Kotlin data class field in JNI

I have a JNI code that intends to modify a field value present in a data class. I'm unable to reference the data class method to do so. Any help is deeply appreciated.

data class User(val name: String, val age: Int, val hasPet : Boolean)

//method in the activity
private fun modifyUserName(){
    val user = User("Vikram", 28, false)
    setSampleObject(user)
}

external fun setSampleObject(sampleUser: User)

//Method in JNI.
extern "C"
JNIEXPORT void JNICALL
Java_com_example_samplemvvm_view_nativekit_NativeCPPActivity_setSampleObject(JNIEnv *env,
                                                                         jobject thiz,
                                                                         jobject sample_user) {

 jclass sampleData = env->GetObjectClass(sample_user);
 jfieldID name = env->GetFieldID(sampleData,"getName","Ljava/lang/String;");
 env -> SetObjectField(sample_user,name,env->NewStringUTF("Test"));
 }

The getName method in the double quotation in the JNI method is displayed in red colour and the application crashes with the following error.

JNI DETECTED ERROR IN APPLICATION: JNI NewStringUTF called with pending exception 
java.lang.NoSuchFieldError: no "Ljava/lang/String;" field "getName" in class 
"Lcom/example/samplemvvm/view/nativekit/user/User;" 
like image 721
Vikram Ragu Avatar asked Jan 20 '26 17:01

Vikram Ragu


1 Answers

You have:

jfieldID name = env->GetFieldID(sampleData,"getName","Ljava/lang/String;");

However, getName() would be the name of the generated JVM method that serves as the getter for that property. The backing field would be named name. So, if you really want the field, change "getName" to "name".

You might want to consider switching to look up the getName() method, though. That way, if you override the getter in your Kotlin class, your JNI uses the overridden function.

like image 99
CommonsWare Avatar answered Jan 22 '26 17:01

CommonsWare



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!