Advanced JNI Coding

The RPG IV compiler support for calling Java™ methods and for writing RPG native methods hides almost all the JNI coding from the RPG programmer. However, RPG's support is not necessarily the most efficient. For example, it always converts arrays between RPG and Java on calls and on entry and exit from native methods, but you may want to handle your own array conversions to improve performance.

The RPG support only gives you access to Java methods. If you want to access the fields in a class, you would have to add "get" and "set" methods to the Java class, or do JNI coding (see Accessing Fields in Java Classes).

Figure 1 is an example of a JNI call in RPG.

Figure 1. JNI Call in RPG
 /COPY JNI
D objectId        s                   like(jobject)
D methodId        s                   like(jmethodID)
D string          s                   like(jstring)
D parms           ds                   likeds(jvalue) dim(3)

 /free
  parms(1).i = 10;                // parameter 1 is an int
  parms(2).l = refToInt(string);  // parameter 2 is an object
  parms(3).d = 2.5e3;             // parameter 3 is a double
  CallVoidMethodA (JNIEnv_P : objectId : methodId : parms);
 /end-free

Note that the pointer JNIEnv_P is defined in the JNI /COPY file.