"GetObjectClass "方法和 "FindClass "方法的区别和用法

 2023-01-20    305  

问题描述

在提供的Java本机接口中

jclass class= (*env)->FindClass(env,"ClassName");

"GetObjectClass "方法和 "FindClass "方法的区别和用法

jclass class= (*env)->GetObjectClass(env,"ClassName");

我想知道这两种方法之间的区别,以及如何使用类名来找到类别以及它可以为null的情况.

推荐答案

GetObjectClass允许您检索对象的类,不知道类名称. GetObjectClass的第二个参数是jobject,而不是类名.

另一方面,如果您可以指定类名,则FindClass为您提供了类参考.

因此,两个函数的结果给出了类参考.区别是每种方法的输入(参数).

其他推荐答案

可以在本机函数中使用GetObjectClass()函数来检索对本机函数定义的对象的引用.然后,您使用此引用访问对象中的字段.

例如,如果您有一个带有简单变量的Java类,并声明了本机函数.

public class helloworld {
    public native int dataGet ();
    int  myIntThing;
}

然后在某个时候您使用此类创建一个对象,如下所示

helloworld myWorld = new helloworld();
int jjj = myWorld.dataGet();

然后在本机应用程序库中,您可以具有以下功能:

JNIEXPORT jint JNICALL Java_helloworld_dataGet (JNIEnv *env, jobject obj)
{
    jclass helloworld_obj = (*env)->GetObjectClass(env, obj);
    // get the old value of the object variable myIntThing then update it
    // with a new value and return the old value.
    jfieldID fid = (*env)->GetFieldID (env, helloworld_obj, "myIntThing", "I");  // find the field identifier for the myIntThing int variable
    jint  myInt = (*env)->GetIntField (env, obj, fid);  // get the value of myIntThing
    (*env)->SetIntField (env, obj, fid, 3);  // set the value of myIntThing
    // we have modified the object's myIntThing variable now return the old value
    return myInt;
}

注意

一个谨慎的词.您可能会认为您实际上可以探究是否通过检查函数GetFieldID()返回的值在对象中定义字段不是无效的,但是我的经验是使用GetFieldID()指定不在中的变量或字段一旦JNI函数返回,该对象将导致Java VM终止.我的测试是1.6,所以这可能已经改变了,但是它也可能是安全功能.

以上所述是小编给大家介绍的"GetObjectClass "方法和 "FindClass "方法的区别和用法,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对77isp云服务器技术网的支持!

原文链接:https://77isp.com/post/26081.html

=========================================

https://77isp.com/ 为 “云服务器技术网” 唯一官方服务平台,请勿相信其他任何渠道。