Use JNI to Create, Populate and Return a Java Class Instance(使用 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.
");
}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 构造函数,否则您不需要调用 setId 和 setCache 方法 - 这只会使您的代码复杂化,因为您将必须为那些调用 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 类实例的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:使用 JNI 创建、填充和返回 Java 类实例
基础教程推荐
- Spring AOP错误无法懒惰地为此建议构建thisJoinPoin 2022-09-13
- 无法复制:“比较方法违反了它的一般约定!" 2022-01-01
- 使用堆栈算法进行括号/括号匹配 2022-01-01
- 如何对 Java Hashmap 中的值求和 2022-01-01
- 问题http://apache.org/xml/features/xinclude测试日志4j 2 2022-01-01
- REST Web 服务返回 415 - 不支持的媒体类型 2022-01-01
- 存储 20 位数字的数据类型 2022-01-01
- 修改 void 函数的输入参数,然后读取 2022-01-01
- RabbitMQ:消息保持“未确认"; 2022-01-01
- Struts2 URL 无法访问 2022-01-01
