使用JNI创建,填充和返回Java类实例 [英] Use JNI to Create, Populate and Return a Java Class Instance

查看:92
本文介绍了使用JNI创建,填充和返回Java类实例的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用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.\n");
         }else{
            printf("Found class.\n");
         }

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

        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 ,你提供了两个arg构造函数的签名。因此,当你调用 NewObject时,你只需要传递 jstring jbytearray code> - 例如:

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);

您无需拨打 setId setCache 方法,除非你决定调用0-arg构造函数 - 这只会使你的代码复杂化,因为你必须调用 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.

这篇关于使用JNI创建,填充和返回Java类实例的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆