tags:

views:

315

answers:

2

I'd like to have a nice, tidy way of expressing the following java code as JNI:

try {
    SomeMethod ();
}
catch (ExceptionType1 e) {
    SomeAction ();
}
catch (ExceptionType2 e) {
    SomeAction ();
}
catch (ExceptionType3 e) {
    SomeAction ();
}

Is there a tidy JNI patter for doing this? At present, I have this:

java_class = (*env)->FindClass (env, EXCEPTION_CLASS_NAME);
if (java_class == NULL) {
    *error_type_ref = ERROR_TYPE_FATAL;
    *exception_code_ref = EU_StrSprintf ("Class not found: %s", EXCEPTION_CLASS_NAME);
    cleanup ();
}
if ((*env)->IsInstanceOf (env, exception, java_class)) {
    SomeAction ();
    cleanup ();
}

And, of course, this reoccurs for each exception so handled. There has to be a better way. Any recommendations? I'm not interested in porting all of my existing code over to JNA, so I'd like a pattern that can be implemented home-grown, so to speak.

A: 

There has to be a better way

Template pattern, may be?

Vladimir Dyuzhev
+1  A: 

To expand on my comment on C vs C++.

I'd try something like this in C++ (nb: completely untested, and probably doesn't compile as is!)

class JavaClass {

    private:
        jclass cls;
        JNIEnv *env;

    public:
        JavaClass(JNIEnv *env, const char *className) {
            this.env = env;
            cls = env->FindClass(className);
            // handle errors
        }

        ~JavaClass() {
            env->DeleteLocalRef(cls);
        }

        bool isInstanceOf(jobject obj) {
            return env->IsInstanceOf(obj, cls);
        }
};

The client code would then look something like:

JavaClass ext1(env, "ExceptionType1");
JavaClass ext2(env, "ExceptionType2");
JavaClass ext3(env, "ExceptionType3");

SomeMethod();

if (ex = env->ExceptionOccurred()) {
    if (ext1.isInstanceOf(ex)) {
        doSomething();
    } else if (ext2.isInstanceOf(ex)) {
        doSomething();
    } else if (ext3.isInstanceOf(ex)) {
        doSomething();
    }
}

(Note that the semantics of this isInstanceOf() function are bass-ackwards - in this one it's "class.instanceof(object)", instead of "object instanceof class").

Alnitak
It's obviously a nice solution, rendered useless by my programming language being C :)
Chris R
oh well, you can't please everyone :)
Alnitak