使用 JNI 创建、填充和返回 Java 类实例

2022-01-25 00:00:00 java java-native-interface

我正在尝试使用 JNI 函数来创建 Java 类并使用 DeviceId.java 构造函数方法设置该类的一些属性.我可以使用 GetMethodID 获取构造函数方法,但是如何创建 Device.java 的新实例然后设置属性(setId 和 setCache).目标是向调用者返回一个完全填充的 Device.java 对象实例.有什么想法吗?

I'm trying to use a JNI function to create a Java class and set some properties of that class using the DeviceId.java constructor method. I'm able to get the constructor method using the GetMethodID, but how would I create a new instance of Device.java and then set the properties (setId and setCache). The goal is to return a fully populated instance of Device.java Object to the caller. Any ideas?

JNI 函数:

 JNIEXPORT jobject JNICALL Java_com_test_getID(JNIEnv *env, jclass cls) 
    {
        jmethodID cnstrctr;
        jclass c = (*env)->FindClass(env, "com/test/DeviceId");
        if (c == 0) {
            printf("Find Class Failed.
");
         }else{
            printf("Found class.
");
         }

        cnstrctr = (*env)->GetMethodID(env, c, "<init>", "(Ljava/lang/String;[B)V");
        if (cnstrctr == 0) {
            printf("Find method Failed.
");
        }else {
            printf("Found method.
");
        }

        return (*env)->NewObject(env, c, cnstrctr);
    }

Java 类:

package com.test;

public class DeviceId {
    private String id;
    private byte[] cache;

        public DeviceId(){}
    public DeviceId(String id, byte[] cache){
        this.id=id;
        this.cache=cache;
    }

    public byte[] getCache() {
        return cache;
    }

    public void setCache(byte[] cache) {
        this.cache = cache;
    }

    public String getId() {
        return id;
    }

    public void setId(String id) {
        this.id = id;
    }   
}

推荐答案

当您调用 GetMethodID 时,您为双参数构造函数提供了签名.因此,您只需在调用 NewObject 时传递您的 jstring 和一个 jbytearray - 例如:

When you called GetMethodID, you provided the signature for the two-arg constructor. Thus, you just need to pass your jstring and a jbytearray when you call NewObject - for example:

return (*env)->NewObject(env, c, cnstrctr, id, cache);

除非您决定调用 0-arg 构造函数,否则您不需要调用 setIdsetCache 方法 - 这只会使您的代码复杂化,因为您将必须为那些调用 GetMethodID 并调用它们.沿您当前的路线继续行驶更简单.

You don't need to call the setId and setCache methods unless you decide to call the 0-arg constructor - and that just complicates your code since you'll have to call GetMethodID for those and call them. Simpler to continue down the route you're on.

相关文章