Question

I have a Java class that may be subclassed to add an additional field. There is a corresponding C++ JNI method that will interact with that field. However, I want the JNI code to handle both the base class and the subclass, which means it must detect whether the field is present.

My (simplified) JNI code looks like this:

fid = j.GetFieldID( jc, UTF8_SECPARM, SIG_SECPARM );
if ( fid == 0 ) return;
... continue with fid ...

Although the GetFieldID() method returns NULL, the application gets an exception at some further point in processing, that is seemingly unrelated to this code. Nevertheless, it is somehow related because if I just return before the GetFieldID() method, there is no exception.

How can one reliably test for the presence of a field or method in an object from JNI code?

Was it helpful?

Solution

It turns out that although the GetFieldID() method returns NULL, there is also a Java exception generated that must be handled.

The solution is to check for an exception and clear (or handle) it. The simplest solution is this:

fid = j.GetFieldID( jc, UTF8_SECPARM, SIG_SECPARM );
if ( JNI_TRUE == j.ExceptionCheck() ) {
    j.ExceptionClear();
    return;
}
... continue with fid ...
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top