Java JNI 调用 FindClass 在 C++ 程序中失败

Java JNI 调用 FindClass 在 C++ 程序中失败

我正在尝试关注教程从 C++ 程序调用 Java 类。Java 虚拟机已实例化,但对 FindClass 的调用失败。代码示例直接来自教程:

我的测试.java

public class MyTest {
    private static int magic_counter=777;

    public static void mymain() { 
       System.out.println("Hello, World in java from mymain");
       System.out.println(magic_counter);
    }
}

主程序

#include <jni.h>
#include <iostream>


using namespace std;
int main()
{
    JavaVM *jvm;
    JNIEnv *env;
    JavaVMInitArgs vm_args;
   JavaVMOption* options = new JavaVMOption[1];
   options[0].optionString = "-Djava.class.path=./";
   vm_args.version = JNI_VERSION_1_6;
   vm_args.nOptions = 1;
   vm_args.options
   = options;
   vm_args.ignoreUnrecognized = false;

   jint rc = JNI_CreateJavaVM(&jvm, (void**)&env, &vm_args);
   delete options;   
   if (rc != JNI_OK) {
         std::cin.get();
         exit(EXIT_FAILURE);
   }

   cout << "JVM load succeeded: Version ";
   jint ver = env->GetVersion();
   cout << ((ver>>16)&0x0f) << "."<<(ver&0x0f) << endl;

   jclass cls2 = env->FindClass("MyTest");  
   if(cls2 == nullptr) {
       cerr << "ERROR: class not found !";
   }
   else {
       cout << "Class MyTest found" << endl;
       jmethodID mid = env->GetStaticMethodID(cls2, "mymain", "()V");  
       if(mid == nullptr)
           cerr << "ERROR: method void mymain() not found !" << endl;
       else {
           env->CallStaticVoidMethod(cls2, mid);                      
           cout << endl;
       }
   }

   jvm->DestroyJavaVM();
   cin.get();
}

g++ 命令:

g++ -I/usr/lib/jvm/java-8-openjdk-amd64/include -I/usr/lib/jvm/java-8-openjdk-amd64/include/linux -L/usr/lib/jvm/java-8-openjdk-amd64/jre/lib/amd64/server  main.cpp -o SearchEngineCpp -ljvm

我运行javac SearchEngine.java来创建类文件。

我究竟做错了什么?

答案1

如果您的系统上有多个版本的 JDK,并且类编译器的默认 Java 版本与您链接可执行文件的版本javac不同,则可能会出现这种情况。libjvm.so

例如,在我的 18.04 系统上:

$ update-alternatives --list javac
/usr/lib/jvm/java-11-openjdk-amd64/bin/javac
/usr/lib/jvm/java-8-openjdk-amd64/bin/javac

$ javac -version
javac 11.0.6

然后

$ javac MyTest.java
$
$ LD_LIBRARY_PATH=/usr/lib/jvm/java-8-openjdk-amd64/jre/lib/amd64/server ./SearchEngineCpp 
JVM load succeeded: Version 1.8
ERROR: class not found !

您可以通过明确调用适当的 Java 编译器来解决这个问题。

$ /usr/lib/jvm/java-8-openjdk-amd64/bin/javac MyTest.java
$
$ LD_LIBRARY_PATH=/usr/lib/jvm/java-8-openjdk-amd64/jre/lib/amd64/server ./SearchEngineCpp 
JVM load succeeded: Version 1.8
Class MyTest found
Hello, World in java from mymain
777

对于持久的系统范围解决方案,请使用该update-alternatives机制选择适当的 Java 版本:

sudo update-alternatives --config java
sudo update-alternatives --config javac
sudo update-alternatives --config javap

相关内容