27장. 자바 클래스의 인스턴스 필드 찾기
$ vi FindInstanceField.cpp#include <jni.h>
#include <iostream>
void printPrivateFieldOfThiz
(
JNIEnv *env,
jobject thiz
)
{
//find the class of this
jclass thizClass = env->GetObjectClass(thiz);
if(thizClass == nullptr) {
std::cout << "Failed to find the class of thiz" << std::endl;
return;
}
//find the private name field
jfieldID nameID = env->GetFieldID(thizClass, "name", "Ljava/lang/String;");
if(nameID == nullptr) {
std::cout << "Failed to find the name field in the thiz" << std::endl;
return;
}
jstring name = static_cast<jstring>( env->GetObjectField(thiz, nameID) );
if(name == nullptr) {
std::cout << "Failed to get the reference of the name field" << std::endl;
return;
}
//convert java-string to c-string
const char *cName = env->GetStringUTFChars(name, nullptr);
if(cName == nullptr)
return;
std::cout << "I found [ " << cName << " ] !!!" << std::endl;
env->ReleaseStringUTFChars(name, cName);
//change the name value
jstring newName = env->NewStringUTF("Jerry Boy");
if(newName == nullptr)
return;
env->SetObjectField(thiz, nameID, newName);
}
JNIEXPORT jint JNICALL JNI_OnLoad
(
JavaVM *vm,
void *reserved
)
{
JNIEnv *env;
if(vm->GetEnv(reinterpret_cast<void**>(&env), JNI_VERSION_1_6)) {
return -1;
}
JNINativeMethod nm[1] ={
{
const_cast<char*>("printPrivateFieldOfThiz"),
const_cast<char*>("()V"),
reinterpret_cast<void*>(printPrivateFieldOfThiz)
}
};
jclass cls = env->FindClass("Client");
env->RegisterNatives(cls, nm, 1);
return JNI_VERSION_1_6;
}Last updated