我正在编写一个程序,我使用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类时,我应该做些什么?怎么了?有什么想法吗?
答案 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()
失败。