在Qt中調用Java接口可以通過Qt的Java Native Interface (JNI)來實現。
以下是一個簡單的示例,演示了如何在Qt中調用Java接口傳取數據:
public interface MyInterface {
public String getData();
}
javac MyInterface.java
javah
命令生成JNI頭文件(例如:MyInterface.h):javah -jni MyInterface
#include <jni.h>
#include <QDebug>
class JavaInterface {
public:
JavaInterface(JNIEnv *env);
~JavaInterface();
QString getData();
private:
JavaVM *m_javaVM;
jobject m_javaObject;
};
JavaInterface::JavaInterface(JNIEnv *env) {
env->GetJavaVM(&m_javaVM);
jclass javaClass = env->FindClass("com/example/MyInterface");
jmethodID javaConstructor = env->GetMethodID(javaClass, "<init>", "()V");
m_javaObject = env->NewObject(javaClass, javaConstructor);
}
JavaInterface::~JavaInterface() {
JNIEnv *env;
m_javaVM->AttachCurrentThread((void **)&env, NULL);
env->DeleteGlobalRef(m_javaObject);
}
QString JavaInterface::getData() {
JNIEnv *env;
m_javaVM->AttachCurrentThread((void **)&env, NULL);
jmethodID getDataMethod = env->GetMethodID(env->GetObjectClass(m_javaObject), "getData", "()Ljava/lang/String;");
jstring javaString = (jstring)env->CallObjectMethod(m_javaObject, getDataMethod);
const char *nativeString = env->GetStringUTFChars(javaString, 0);
QString result = QString::fromUtf8(nativeString);
env->ReleaseStringUTFChars(javaString, nativeString);
return result;
}
int main(int argc, char *argv[]) {
QCoreApplication app(argc, argv);
JavaVMOption options[1];
JavaVMInitArgs vm_args;
JavaVM *javaVM;
JNIEnv *env;
options[0].optionString = "-Djava.class.path=/path/to/java/classes";
vm_args.version = JNI_VERSION_1_6;
vm_args.nOptions = 1;
vm_args.options = options;
vm_args.ignoreUnrecognized = JNI_FALSE;
JNI_CreateJavaVM(&javaVM, (void **)&env, &vm_args);
JavaInterface javaInterface(env);
QString data = javaInterface.getData();
qDebug() << "Data from Java: " << data;
javaVM->DestroyJavaVM();
return app.exec();
}
注意:
請將/path/to/java/classes
替換為包含MyInterface.class的目錄路徑。
如果你的Java類位于不同的包,需要在FindClass
方法中傳入完整的類名(例如:com.example.MyInterface)。
以上代碼僅供參考,實際使用時可能需要根據具體的需求進行修改和調整。