Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check for presence of optional field or method in Java Class from JNI code

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?

like image 881
Scott Avatar asked Dec 26 '13 18:12

Scott


1 Answers

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 ...
like image 149
Scott Avatar answered Sep 21 '22 00:09

Scott