"GetObjectClass"方法和"FindClass"方法的区别和用法
"GetObjectClass" method and "FindClass" method difference and usage
提供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版本,所以这可能有变化,但它也可能是一个安全特性。
相关文章:
- 为不同配置设置MSVC_RUNTIME_LIBRARY的正确方法是什么
- 通过方法访问结构
- 最小硬币更换问题(自上而下方法)
- C++为构建时间获取QDateTime的可靠方法
- 在C#中处理C++指针而不使用unsafe的最佳方法
- 处理多个异常集合的C++方法
- 如果C++类在类方法中具有动态分配,但没有构造函数/析构函数或任何非静态成员,那么它仍然是POD类型吗
- 有什么方法可以遍历结构吗
- 当类在C++中定义时,有什么方法可以"register"类吗?
- 在C++中,将大的无符号浮点数四舍五入为整数的最佳方法是什么
- 实现无开销push_back的最佳方法是什么
- 类作用域的类型别名"using":[何时]方法中的用法可以先于类型别名?
- 复制构造函数方法的用法
- 为什么"Warning X4000: use of potentially uninitialized variable"显示多个常用方法的用法?
- 原子类对象方法用法
- Recv 方法用法
- 命名参数习惯用法,使用指向类私有方法的指针
- 获取源代码树中 boost:shared_ptr get 方法的所有用法的列表
- 指针和方法的奇怪用法
- "GetObjectClass"方法和"FindClass"方法的区别和用法