无法在 JNI 中引用 Kotlin 数据类字段
我有一个JNI代码,该代码打算修改数据类中存在的字段值。 我无法参考数据类方法。任何帮助将得到深深的赞赏。
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"));
}
JNI方法中双引号中的GetName方法以红色显示,并且应用程序崩溃了,并带有以下错误。
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;"
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;"
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您有:
但是,
getName()
将是生成的JVM方法的名称,该方法是该属性的Getter。备份字段将被命名为名称
。因此,如果您真的想要该字段,请将“ getName”
更改为“ name”
。您可能需要考虑切换以查找
getName()
方法。这样,如果您覆盖Kotlin类中的Getter,则JNI使用覆盖功能。You have:
However,
getName()
would be the name of the generated JVM method that serves as the getter for that property. The backing field would be namedname
. 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.