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

"GetObjectClass" method and "FindClass" method difference and usage

本文关键字:方法 用法 区别 FindClass GetObjectClass      更新时间:2023-10-16

提供java本地接口

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

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

我想知道这两个方法之间的区别,以及它如何通过使用类名找到一个类,以及在什么情况下它可以为空

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()返回的值是否为NULL来实际探测是否在对象中定义了字段,但是我的经验是,使用GetFieldID()指定不在对象中的变量或字段将导致Java VM在JNI函数返回后终止。我的测试是在1.6版本,所以这可能有变化,但它也可能是一个安全特性。