从JNI调用Java Enum方法



我有一个场景,需要在本机代码中调用enum方法。此枚举是用Java定义的。

public enum Pool {
JNIPOOL(new SomePoolStrategyImp()),
UIPOOL(new RandomPoolStrategyImp());
private PoolStrategy poolStrategy;
Pool(PoolStrategy poolStrategy) {
this.poolStrategy = poolStrategy;
}
public Bitmap getBitmap(int width, int height) {
// some logic
// return poolStrategy.getBitmap(width, height);
}
}

我有可以从JNI调用对象方法的引用,但在我的情况下,我需要调用已经创建的对象方法。就像我需要从本机代码调用JNIPOOL.getBitmap()一样。有人能帮我吗?我只是想办法或任何现有的博客,可以帮助我在这方面。

谢谢!

正如我已经说过的,枚举常量只是一个字段。

为了测试我的解决方案,我使用了一个具有以下签名的本地方法:

private static native Bitmap callBitmap(int width, int height);

在类别CCD_ 2中。这是C++中的本机代码:

JNIEXPORT jobject JNICALL Java_test_JNITest_callBitmap
(JNIEnv * env, jclass clazz, jint width, jint height) {
// Get a reference to the class
jclass poolc = env->FindClass("test/Pool");
// get the field JNIPOOL
jfieldID jnipoolFID = env->GetStaticFieldID(poolc, "JNIPOOL", "Ltest/Pool;");
jobject jnipool = env->GetStaticObjectField(poolc, jnipoolFID);
// Find the method "getBitmap", taking 2 ints, returning test.Bitmap
jmethodID getBitmapMID = env->GetMethodID(poolc, "getBitmap", "(II)Ltest/Bitmap;");
// Call the method.
jobject result = env->CallObjectMethod(jnipool, getBitmapMID, width, height);
return result;
}

最新更新