我试过下面的例子。我有两个本机方法setMessage和printMessage。我在main方法中创建了两个ClassA对象,在a1对象上创建了setMessage,并且在a2对象上获得了相同的消息范围(参见输出)。
如何使用新范围创建新的ClassA对象。
ClassA.c
#include "ClassA.h"
char * message ;
JNIEXPORT void JNICALL Java_ClassA_setMessage (JNIEnv * env , jobject obj, jstring msg){
message = (*env)->GetStringUTFChars(env, msg, 0);
}
JNIEXPORT void JNICALL Java_ClassA_printMessage (JNIEnv * env, jobject obj){
printf("%s\n", message);
}
ClassA.java
public class ClassA {
static {
System.loadLibrary("myapp");
}
public native void setMessage(String msg);
public native void printMessage();
}
ClassB.java
public class ClassB {
public static void main(String[] args) {
ClassA a1 = new ClassA();
System.out.print("Print message with out setMessage() By a1 :");
a1.printMessage();
a1.setMessage("I am a1");
System.out.print("Print message after setMessage() By a1 : ");
a1.printMessage();
ClassA a2 = new ClassA();
System.out.print("Print message with out setMessage() By a2 :");
a2.printMessage();
a2.setMessage("I am a2");
System.out.print("Print message after setMessage() By a2 : ");
a2.printMessage();
}
}
::::输出::::
Print message with out setMessage() By a1 : (null)
Print message after setMessage() By a1 : I am a1
Print message with out setMessage() By a2 : I am a1
Print message after setMessage() By a2 : I am a2
答案 0 :(得分:1)
在创建新对象之前清除“消息”。