java 在 C 中使用 JNI 从对象中获取对象
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/15783344/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Get object from an object with JNI in C
提问by user1151874
public class Student
{
private People people;
private Result result;
private int amount;
}
Here is the sample of the class in Java; in C, I tried to get the "people" in "Student", but I failed. However, I am able to get int type "amount" from "Student".
这是 Java 类的示例;在 C 中,我试图获取“学生”中的“人”,但失败了。但是,我可以从“Student”中获取 int 类型“amount”。
jobject getObjectFromObject(JNIEnv *env, jobject obj, const char * fieldName)
{
jfieldID fid; /* store the field ID */
jobject i;
/* Get a reference to obj's class */
jclass cls = (*env)->GetObjectClass(env, obj);
/* Look for the instance field s in cls */
fid = (*env)->GetFieldID(env, cls, fieldName, "L");
if (fid == NULL)
{
return 0; /* failed to find the field */
}
/* Read the instance field s */
i = (*env)->GetObjectField(env, obj, fid);
return i;
}
I am trying to pass "people" as a fieldName into the method, but it still gives the following error: "java.lang.NoSuchFieldError: people"
我试图将“people”作为 fieldName 传递到方法中,但它仍然给出以下错误:“java.lang.NoSuchFieldError: people”
回答by mbrenon
As documented here, in the GetFieldID
method you can't use "L" alone as a type signature, you have to specify the class name after that.
如此处所述,在GetFieldID
您不能单独使用“L”作为类型签名的方法中,您必须在此之后指定类名。
For example if you want to specify that the argument is a String
, you'll have to use Ljava/lang/String;
(The final semicolon is part of the signature!).
例如,如果您想指定参数是 a String
,则必须使用Ljava/lang/String;
(最后一个分号是签名的一部分!)。
For your custom class named People
, supposing it's in the package your.package.name
, you'll have to use Lyour/package/name/People;
as a type signature.
对于名为 的自定义类People
,假设它在包中your.package.name
,则必须Lyour/package/name/People;
用作类型签名。