Search code examples
javaoraclejvmjava-native-interfacejvmti

JVMTI - Get object for field in class


I'm having a problem with JVMTI.

I would like to access each static field of a class and tag it. I can get the signature of each field, I can find out if it is static, but I haven't found a method yet to get a jobject for the fields which should get tagged. Here is (shortened) what I have so far:

jint fieldCount;
jfieldID* fields_ptr;
int i = 0;
jint err;

err = (*env)->GetClassFields(env, *klass, &fieldCount, &fields_ptr);

for(i = 0; i < fieldCount; i++)
{
  jfieldID field = fields_ptr[i];
  char* name_ptr;
  char* signature_ptr;
  char* generic_ptr;
  jint accessFlags;

  err = (*env)->GetFieldName(env, *klass, field, &name_ptr, &signature_ptr, &generic_ptr);

  (*env)->GetFieldModifiers(env, *klass, field, &accessFlags);  
  if (accessFlags & 0x0008)
    fprintf(file, "STATIC ");
  else
    fprintf(file, "NOT STATIC ");
  fprintf(file, "Field %s of type %s\n", name_ptr, signature_ptr);
}

//TODO: Something like this:
//if (accessFlags & 0x0008) {
//  jobject obj = (*env)->GetStaticField(env, *klass, field);
//  (*env)->SetTag(env, obj, 1);
//}

What I now need is a method which gives me an jobject based on *klass (jclass) and field (jfieldID) or something similar so I could call SetTag(...) on all static fields. Is there some method for this?

I use this documentation as reference: http://docs.oracle.com/javase/7/docs/platform/jvmti/jvmti.html

Thanks!


Solution

  • I just got a response on Facebook which answers my question.

    Here is the JNI reference: http://docs.oracle.com/javase/8/docs/technotes/guides/jni/spec/functions.html

    There you can find following methods:

    Get<type>Field Routines:
    NativeType Get<type>Field(JNIEnv *env, jobject obj, jfieldID fieldID);
    
    GetStatic<type>Field Routines:
    NativeType GetStatic<type>Field(JNIEnv *env, jclass clazz, jfieldID fieldID);
    

    So I can use GetObjectField() and GetStaticObjectField() which return a jobject which I then can use to tag it.

    My mistake was to only look at the JVMTI documentation instead of also using the JNI reference.