3

I created a JVM using:

Jvm::Jvm(std::string ClassPath = ".")
{
    options = new JavaVMOption[2];
    jvm_args.version = JNI_VERSION_1_6;
    //JNI_GetDefaultJavaVMInitArgs(&jvm_args);
    options[0].optionString = const_cast<char*>("-Djava.compiler=NONE");
    options[1].optionString = const_cast<char*>(("-Djava.class.path=" + ClassPath).c_str());
    jvm_args.nOptions = 2;
    jvm_args.options = options;
    jvm_args.ignoreUnrecognized = false;

    if (JNI_CreateJavaVM(&jvm, reinterpret_cast<void**>(&env), &jvm_args))
    {
        throw std::runtime_error("Failed To Create JVM Instance.");
    }

    delete[] options;
    options = nullptr;
}

Now I want to know if there is a way to enumerate all packages in a jar or all packages loaded by my JVM.

For example, if I wanted to load the main class I'd do:

void CallMain()
{
    JNIEnv* env = jvm.GetEnv();

    jclass MainClass = env->FindClass("mypackage/Main");
    if (MainClass)
    {
        jmethodID MainMethod = env->GetStaticMethodID(MainClass, "main", "([Ljava/lang/String;)V");
        if (MainMethod)
        {
            jclass StringClass = env->FindClass("java/lang/String");
            jobjectArray Args = env->NewObjectArray(0, StringClass, 0);
            env->CallStaticVoidMethod(MainClass, MainMethod, Args);
        }
    }
}

And as you can see, I must specific "mypackage/Main" to load main which resides in a specific package..

However, if I don't know the package Main belongs to, how can I find out? Or how can I get the list of all packages loaded? I don't exactly need to find main. I just want to list all packages.

Any ideas?

Brandon
  • 22,723
  • 11
  • 93
  • 186

1 Answers1

0

I am not aware of any auto-magic solution to this problem. Generally you need to know the package and name of the class you are trying to load unless you are using some kind of factory. In theory you could port something like this to JNI and accomplish your goal. It will be ugly and complicated, but it should work just as well in C as it does in Java.

Community
  • 1
  • 1
Alex Barker
  • 4,316
  • 4
  • 28
  • 47