JNI "NewObject" 用 NULL 值初始化时不会 return NULL?
JNI "NewObject" will not return NULL when initialize it with NULL value?
当我做了一些 testing codes 时,我得到了一些有效的答案,但我发现了一些其他问题(或者只是我认为是)。
代码如下:
JNIEXPORT jint JNICALL test_jni_Native_testSet(JNIEnv *env, jclass type, jobject tdobj)
{
//Create Integer class, get constructor and create Integer object
jclass intClass = env->FindClass(env, "java/lang/Integer");
jmethodID initInt = env->GetMethodID(env, intClass, "<init>", "(I)V");
if (NULL == initInt) return -1;
jobject newIntObj = env->NewObject(env, intClass, initInt, 123);
//Now set your integer into value atttribute. For this, I would
//recommend you to have a java setter and call it in the same way
//as shown above
//clean reference
env->DeleteLocalRef(env, newIntObj);
return 0;
}
如果我将行中的 123 替换为 NULL
jobject newIntObj = env->NewObject(env, intClass, initInt, 123);
在java代码中,我通过这个原生函数设置了一个Integer参数。
如果 env->NewObject 成功调用构造函数,它似乎不会 return NULL。
这意味着我只能用 NULL 分配一个 jobject 而不是调用 NewObject 函数并初始化它将 NULL。
我认为这不是一个好处理。
正如http://docs.oracle.com/javase/1.5.0/docs/guide/jni/spec/functions.html所说:
env->NewObject(...)
RETURNS:
Returns a Java object, or NULL if the object cannot be constructed.
那么,我的问题是:
当我们用 NULL 值初始化对象时,为什么不 return NULL?
函数 NewObject
使用 non-type 安全的可变参数列表。如果将NULL传递给构造函数,它将被解释为整数值0。因此,它将成功构造一个初始化为0的Integer对象.
当我做了一些 testing codes 时,我得到了一些有效的答案,但我发现了一些其他问题(或者只是我认为是)。
代码如下:
JNIEXPORT jint JNICALL test_jni_Native_testSet(JNIEnv *env, jclass type, jobject tdobj)
{
//Create Integer class, get constructor and create Integer object
jclass intClass = env->FindClass(env, "java/lang/Integer");
jmethodID initInt = env->GetMethodID(env, intClass, "<init>", "(I)V");
if (NULL == initInt) return -1;
jobject newIntObj = env->NewObject(env, intClass, initInt, 123);
//Now set your integer into value atttribute. For this, I would
//recommend you to have a java setter and call it in the same way
//as shown above
//clean reference
env->DeleteLocalRef(env, newIntObj);
return 0;
}
如果我将行中的 123 替换为 NULL
jobject newIntObj = env->NewObject(env, intClass, initInt, 123);
在java代码中,我通过这个原生函数设置了一个Integer参数。 如果 env->NewObject 成功调用构造函数,它似乎不会 return NULL。 这意味着我只能用 NULL 分配一个 jobject 而不是调用 NewObject 函数并初始化它将 NULL。
我认为这不是一个好处理。
正如http://docs.oracle.com/javase/1.5.0/docs/guide/jni/spec/functions.html所说:
env->NewObject(...)
RETURNS:
Returns a Java object, or NULL if the object cannot be constructed.
那么,我的问题是:
当我们用 NULL 值初始化对象时,为什么不 return NULL?
函数 NewObject
使用 non-type 安全的可变参数列表。如果将NULL传递给构造函数,它将被解释为整数值0。因此,它将成功构造一个初始化为0的Integer对象.