Loading Multiple Jars on Windows - JNI JNI_CreateJavaVM

纵饮孤独 提交于 2019-12-12 19:23:31

问题


I'm creating a JVM within my C++ application for windows, and I'm unable to convince it to load multiple jars.

My C++ code:

MyClass::MyClass(std::string & classPath) {
    classPath = "-cp "+classPath;   // <--  Won't work with any path or single jar
    //classPath = "-Djava.class.path="+classPath; <-- Only works with single jar
    jvmOptions[0].optionString = (char *)classPath.c_str();
    jvmOptions[1].optionString = "-Xms8m";
    jvmOptions[2].optionString = "-Xmx24m";
    jvmArgs.version = JNI_VERSION_1_6;
    jvmArgs.options = jvmOptions;
    jvmArgs.nOptions = 3;
    jvmArgs.ignoreUnrecognized = JNI_TRUE;
    int jvmInitResult = CreateJavaVM( &jvm, (void**)&environment, &jvmArgs);

    if( jvmInitResult >= 0 ) {
        jclass loadedClass = environment->FindClass( MyClassName.c_str() );
          .....

If I pass a path via my classPath variable to a single JAR, such as "C:\path\myjar.jar", the jclass variable is located fine. However, my Java class requires additional JARs to function, so I need to pass more than one JAR to the jvmOptions. When I try to pass the second, or third JAR, in any of the following ways, the FindClass call now fails.

C:\path\myjar.jar    <--------- FindClass SUCCESS; can't use due to missing jars
C:\path\myjar.jar;C:\path\secondjar.jar  <-----FindClass FAIL
C:\path\myjar.jar:C:\path\secondjar.jar  <-----FindClass FAIL
C:\path\*  <-----FindClass FAIL
C:\path\*.jar  <-----FindClass FAIL
"C:\path\myjar.jar;C:\path\secondjar.jar"  <-----FindClass FAIL
"C:\path\myjar.jar:C:\path\secondjar.jar"  <-----FindClass FAIL

I assume there is another option I'm not thinking of, but this is driving me nuts.


回答1:


You should use -cp to set the class path. I suspect -Djava.class.path= won't do what you think it should.




回答2:


The solution is to not use windows file separators when passing the argument to the program. The \ ends up getting escape sequenced with one or more \ . Changing the argument to unix style file separators correctly loads all of the jars within a directory.

eg:

MyApp "classpath"
MyApp C:\pathtojars\  <-- fails
MyApp C:/pathtojars/  <-- works

Fixed code:

MyClass::MyClass(std::string & classPath )
{
   classPath = "-Djava.class.path="+classPath;
   jvmOptions[0].optionString = (char *)classPath.c_str();
   jvmOptions[1].optionString = "-Xms8m";
   jvmOptions[2].optionString = "-Xmx24m";
   jvmArgs.version = JNI_VERSION_1_6;
   jvmArgs.options = jvmOptions;
   jvmArgs.nOptions = 3;
   jvmArgs.ignoreUnrecognized = JNI_TRUE;
   int jvmInitResult = CreateJavaVM( &jvm, (void**)&environment, &jvmArgs);

   if( jvmInitResult >= 0 )
   {
       jclass loadedClass = environment->FindClass( MyClassName.c_str() );
        .....


来源:https://stackoverflow.com/questions/19059602/loading-multiple-jars-on-windows-jni-jni-createjavavm

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!