josecampos
josecampos

Reputation: 861

How to know whether a class has been initialized or not?

Either with a CustomClassloader or a Java agent + Instrumentation API is quite simple and straightforward to get all classes that have been loaded by the JVM. However, the list of classes that have been initialized does not seem so easy to get. (I actually wonder if there is any way to get it)

So, is there any way to know whether a class has been initialized?

-- Thanks in advance

Upvotes: 5

Views: 564

Answers (1)

vsminkov
vsminkov

Reputation: 11250

I'm not sure about Instrumentation API but one possible way is to use JVMTI GetClassStatus function.

With tool interface you can obtain all classes loaded by JVM and find out those without JVMTI_CLASS_STATUS_INITIALIZED status flag

JavaVM *jvm;
jvmtiEnv *jvmti;
jvmtiError err;

env->GetJavaVM(&jvm);
jvm->GetEnv((void **) &jvmti, JVMTI_VERSION_1_2);

jint classCount = 0;
jclass * classes;

jvmti->GetLoadedClasses(&classCount, &classes);
for (int i = 0; i < classCount; i++) {
    jint classStatus = 0;
    jvmti->GetClassStatus(classes[i], &classStatus);

    if (classStatus != JVMTI_CLASS_STATUS_PRIMITIVE
        && classStatus != JVMTI_CLASS_STATUS_ARRAY
        && classStatus != JVMTI_CLASS_STATUS_ERROR
        && !(classStatus & JVMTI_CLASS_STATUS_INITIALIZED)) {
        // static initializer is not finished yet
    }
}

Upvotes: 4

Related Questions