What's the difference between these two means of getting the PackageName?

1

I have these two code snippets, the two display the same result, so I would like to know what the difference is between them.

1

jclass cls = (*env)->FindClass(env, "android/content/ContextWrapper");
jmethodID mid = (*env)->GetMethodID(env, cls, "getPackageName", "()Ljava/lang/String;");

jstring packageNamei = (jstring)(*env)->CallObjectMethod(env, context, mid);
const char *nativeString = (*env)->GetStringUTFChars(env, packageNamei, 0);
__android_log_print(ANDROID_LOG_INFO, "--packageName--jni--", "%s", nativeString);

2

jclass context_clazz = (*env)->GetObjectClass(env, context);

jmethodID methodID_pack = (*env)->GetMethodID(env, context_clazz, 
"getPackageName", "()Ljava/lang/String;");
jstring application_package = (*env)->CallObjectMethod(env, context, methodID_pack);
const char *str = (*env)->GetStringUTFChars(env, application_package, 0);
__android_log_print(ANDROID_LOG_DEBUG, "JNI", "PackageName: %s\n", str);

Can I use any of them, or is one more recommended?

    
asked by anonymous 15.08.2016 / 23:51

1 answer

1

In case 1

FindClass will get the reference of the class from its name, that is, to get the reference of the class you should know its name and its complete signature. Example of class String :

Name String

Full signature java.lang.String - but you should replace the points with%

In case 2 "java/lang/String" will get the class reference from an object, that is, you do not need to know the name of the class, the object itself contains this information, and GetObjectClass will get the reference of the class to which the object was instantiated. If the class to which this object belongs does not have the method you are looking for, probably GetObjectClass will generate a GetObjectClass exception. The second argument of NoSuchMethodError is the object reference:

jclass GetObjectClass(JNIEnv *env, jobject obj);

Specifically for the code snippet of your second case, the GetObjectClass function can be used in the case of the various classes that have the same method, such as classes that inherit a method from the same parent class. In this way it does not matter which class the instantiated object belongs to, since all classes inherit the same method.

Using them will depend on the purpose of your native function.

Link to more information about class operations functions: JNI Functions

From this information you can judge which one will best suit your needs.

    
18.08.2016 / 16:47