Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

In java native interface provided

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

and

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

I would like to know difference between this two methods and how it find a class by using class name and what kind of situations it can be null.

like image 531
JanithOCoder Avatar asked Mar 10 '14 17:03

JanithOCoder


2 Answers

GetObjectClass allows you to retrieve the class for an object, not knowing the class name. The second argument to GetObjectClass is a jobject, not a class name.

On the other hand, FindClass gives you a class reference if you can specify the class name.

So the result of both function gives the class reference. The difference is the input (argument) to each methods.

like image 124
manuell Avatar answered Nov 15 '22 01:11

manuell


The GetObjectClass() function can be used within a native function to retrieve a reference to the object in which the native function has been defined. You then use this reference to access the fields within the object.

For instance if you have a Java class with a simple variable and a native function declared.

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

and then at some point you use this class to create an object as follows

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

then in the native application library you could have a function like:

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;
}

NOTE

One word of caution. You would think that you could actually probe to see if a field is defined in an object by checking the value returned by the function GetFieldID() is not NULL however my experience is that using GetFieldID() specifying a variable or field that is not in the object will result in the Java VM terminating once the JNI function returns. My testing was with 1.6 so this may have changed however it may also be a security feature.

like image 41
Richard Chambers Avatar answered Nov 15 '22 03:11

Richard Chambers