Java 对象构造函数的 GetMethodID

GetMethodID of constructor of Java object

我有一个与 C++ 的 GetMethodID() 函数相关的简短问题。我一直在 Whosebug 上寻找答案,但找不到。我的主要代码在 Java 中,但对于某些部分我需要 C++。下面的代码是我打算实现的代码的简化,以测试如何在 Java 和 C++ 之间检索和传递对象。最后一期在本篇文章的末尾提出。首先,我介绍实现。

public class ExampleJNI {

static {
    System.loadLibrary("nativeObject");
}

public static void main(String[] args){
     ExampleJNI tmp  = new ExampleJNI();
     Order o = tmp.createOrder(1,2,3,4);

     if (o != null){
         System.out.println(o.toString());
     } else {
         System.out.println("Errors present");
     }
}

// Try passing a list
public native Order createOrder(int a, int b, int c, int d);

}

顺序class定义为:

public class Order {

// Order attributes
public final int a;
public final int b;
public final int c;
public final int d;

private int e;

public Order(int a, int b, int c, int d){
    this.a = a;
    this.b = b;
    this.c = c;
    this.d = d;
}

@Override
public String toString(){
    return a+","+b+","+c+","+d;
}
}

我在 C++ 中有以下实现。

#include "ExampleJNI.h"
#include <iostream>
#include <vector>
/*
 * Class:     ExampleJNI
 * Method:    createOrder
 * Signature: (IIII)LOrder;
 */
JNIEXPORT jobject JNICALL Java_ExampleJNI_createOrder(JNIEnv* env, jobject thisObject,     jint a, jint b, jint c, jint d){

// Get a class reference for Order
jclass cls = env->GetObjectClass(thisObject);

if (cls == NULL){
    std::cout << "Class not found" << std::endl;
    return NULL;
}

// Get the method ID of the constructor whick takes four integers as input
jmethodID cid = env->GetMethodID(cls, "<init>", "(IIII)V");

if (cid == NULL){
    std::cout << "Method not found" << std::endl;
    return NULL;
}

return env->NewObject(cls, cid, a, b, c, d);
}

当我 运行 代码时,打印“找不到方法”,这表明调用 GetMethodID 时出现问题。我还检索到以下异常错误:

Exception in thread "main" java.lang.NoSuchMethodError: <init>
    at ExampleJNI.createOrder(Native Method)
    at ExampleJNI.main(ExampleJNI.java:11)

非常感谢任何关于我应该用什么代替 <init> 的建议!

thisObjectExampleJNI 而不是 Order 所以 GetObjectClass 将 return ExampleJNI 没有你的构造函数寻找。将 GetObjectClass 更改为 env->FindClass("Order")