我构建了一个从本机代码调用java方法的简单示例, 我正在调用某个对象的java方法,但构造函数从不调用。
我的java课程:
public class MyJavaNumber
{
private int num;
public MyJavaNumber()
{
num = 7;
Log.d("MyJavaNumber" , "con");
}
public int getNum() {
Log.d("getNum" , "num = " + num);
return num;
}
}
cpp代码:
extern "C"
{
JNIEXPORT jint JNICALL
Java_nativeex_com_example_nativeex_MainActivity_getIntA(JNIEnv *env, jobject obj);
};
JNIEXPORT jint JNICALL
Java_nativeex_com_example_nativeex_MainActivity_getIntA(JNIEnv *env, jobject obj)
{
jclass localClass = env->FindClass("nativeex/com/example/nativeex/MyJavaNumber");
javaClassRef = (jclass) env->NewGlobalRef(localClass);
javaMethodRef = env->GetMethodID(javaClassRef, "getNum", "()I");
jobject javaObjectRef = env->NewObject(javaClassRef, javaMethodRef);
return env->CallIntMethod(javaObjectRef, javaMethodRef);
}
MainActivity:
public class MainActivity extends AppCompatActivity {
public native int getIntA();
static
{
System.loadLibrary("ndktest");
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Log.d("onCreate", "" + getIntA());
}
}
日志输出为:
07-13 14:00:01.049 6797-6797/nativeex.com.example.nativeex D/getNum: num = 0
07-13 14:00:01.049 6797-6797/nativeex.com.example.nativeex D/getNum: num = 0
07-13 14:00:01.049 6797-6797/nativeex.com.example.nativeex D/onCreate: 0
我如何调用对象上的方法,但构造函数从不调用?
答案 0 :(得分:2)
javaMethodRef = env->GetMethodID(javaClassRef, "getNum", "()I");
jobject javaObjectRef = env->NewObject(javaClassRef, javaMethodRef);
javaMethodRef
无法接受,spec说NewObject
:
构造一个新的Java对象。方法ID指示哪个 要调用的构造函数方法。必须通过致电获取此ID GetMethodID()以
<init>
作为方法名称,void
(V
)作为 返回类型。
答案 1 :(得分:0)
尝试使用param&#34; obj&#34;在方法Java_nativeex_com_example_nativeex_MainActivity_getIntA(JNIEnv * env,jobject obj)中 这个参数是MyJavaNumber的一个例子。调用构造函数时,它也会让我感到困惑。