Home > OS >  Unable to refer Kotlin data class field in JNI
Unable to refer Kotlin data class field in JNI

Time:04-04

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;" 

CodePudding user response:

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.

  • Related