繁体   English   中英

从JNI调用Java枚举方法

[英]Call Java Enum method from JNI

我有一种情况,我需要在本机代码中调用枚举方法。 这个枚举是用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);

在类test.JNITest 这是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;
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM