使用JNI在.jar中查找Java类

时间:2013-08-13 14:47:22

标签: java c++ jar java-native-interface

我正在编写一个程序,我使用JNI从C ++代码调用Java函数。如果直接使用.class文件,我的程序运行正常,但是当我将它添加到jar文件时FindClass失败。例如,这很好用

    std::string stdOpt = "-Djava.class.path=<path_to_jar>/dependency.jar;<path_to_class>";

    boost::scoped_array<char> opt(new char[stdOpt.size() + 1]);
    std::copy(stdOpt.begin(), stdOpt.end(), opt.get());
    opt[stdOpt.size()] = '\0';
    options[0].optionString = opt.get();

    JavaVMInitArgs vm_args;
    memset(&vm_args, 0, sizeof(vm_args));
    vm_args.version = JNI_VERSION_1_6;
    vm_args.nOptions = 1;
    vm_args.options = options;
    long status = JNI_CreateJavaVM(&m_pJavaVirtualMachine, (void**)&m_pJavaEnvironment, &vm_args);
    if (status != JNI_OK)
        throw std::logic_error("Cannot start Java Virtual Machine");

    m_class = m_pJavaEnvironment->FindClass("MyClass");
    if(m_class == 0)
        throw std::logic_error("Cannot find Java class");

但是这个失败了

    std::string stdOpt = "-Djava.class.path=<path_to_jar>/dependency.jar;<path_to_jar>/myjar.jar";

    boost::scoped_array<char> opt(new char[stdOpt.size() + 1]);
    std::copy(stdOpt.begin(), stdOpt.end(), opt.get());
    opt[stdOpt.size()] = '\0';
    options[0].optionString = opt.get();

    JavaVMInitArgs vm_args;
    memset(&vm_args, 0, sizeof(vm_args));
    vm_args.version = JNI_VERSION_1_6;
    vm_args.nOptions = 1;
    vm_args.options = options;
    long status = JNI_CreateJavaVM(&m_pJavaVirtualMachine, (void**)&m_pJavaEnvironment, &vm_args);
    if (status != JNI_OK)
        throw std::logic_error("Cannot start Java Virtual Machine");

    m_class = m_pJavaEnvironment->FindClass("MyClass");    //m_class=NULL
    if(m_class == 0)
        throw std::logic_error("Cannot find Java class");  //throwing exception 

当我尝试从.jar获取Java类时,我应该做些什么?怎么了?有什么想法吗?

2 个答案:

答案 0 :(得分:5)

如果您的类在一个包中,请在调用FindClass时包含该包,而不是类路径。

 m_class = m_pJavaEnvironment->FindClass( "com/mycompany/mypackage/MyClass" );

答案 1 :(得分:3)

事实证明,问题不在代码中。代码很好。问题在于制作.jar文件。我正在使用Visual Studio并自动编译.java.class并添加.class.jar文件我添加到预构建事件到项目。所以在创建.jar文件之前,我应该像这样指定当前目录

  

cd“&lt; _directory_where_.class_file_is_located&gt;”

     

jar cf myjar.jar MyClass.class

否则MyClass.class已添加到.jar文件中,其文件夹为绝对路径,FindClass()失败。