Paul C. Williams

Interfacing Technology & Business
View Paul Williams's profile on LinkedIn
StackOverflow
 3.3k 

Wednesday, November 20, 2013

Calling Java methods from RPG programs

Lately I've been working with a client to help them bridge a gap between their existing RPG programs and a Java utility library used to execute some network APIs.

There are a lot of resources around, but there is quite a bit of confusion about the specifics of the call semantics between the purely procedural RPG code, and the object-oriented behavior of Java code.

In Java, there's a magic identifier this, which references the current instance.  Because RPG lacks the concept of an Object-Method call, it cannot supply the reference to the object that becomes this.  Instead, when calling from RPG, a parameter is inserted before the first parameter.

As an example, given the following simple Java class:

public class Foo {
    private String bar;
    public Foo() {
        this.bar = null;
    }
    public void setBar( String bar) {
        this.bar = bar;
    }
    public String getBar() {
        return this.bar;
    }
}

The RPG to set up and execute the java method from RPG looks like this:

 * Define a prototype for the 
D fooObj          PR              O   EXTPROC(*JAVA:
D                                      'Foo':
D                                      *CONSTRUCTOR)
 * define a constructor for strings
D makestring      PR              O    EXTPROC(*JAVA:
D                                       'java.lang.String':
D                                       *CONSTRUCTOR)
D    bytes                      30A    CONST VARYING
 * Define a prototype for the setBar method from the Foo object.
D setBar          PR              O    EXTPROC(*JAVA:
D                                       'Foo':
D                                       'setBar')
D                                      CLASS(*JAVA:'java.lang.String')
D                                      CONST
 * Define a string to hold the bar parameter...
D bar             S               O    CLASS(*JAVA:'java.lang.String')
 * Define a field to hold the foo object
D fooInst         S               O    CLASS(*JAVA:'Foo')
 *
 * Define instances
 *
C                   EVAL      bar = makestring('123456789012345678901234567890')
C                   EVAL      fooInst = fooObj()
 *
 * Call the setBar method on the Foo object.  The prototype only defines
 * One parameter, but there is an implied first parameter that populates
 * the java "this" identifier.
 *
C                   EVAL      setBar(fooInst:bar)

I'm not an RPG programmer, nor do I have access to an AS/400 to test my code.  Leave me a comment if this needs to be improved and I'll be sure to make the necessary edits.

References:

No comments:

Post a Comment