Using the Java Assembly in Development

The Java assembly is used to execute Java functions, to get results of their work and to further work with obtained data. Depending on the complexity and the method of implementation of executed Java code in Fore, the following methods can be used:

To execute Java methods, one should create their JNI signature. The following table provides main type signatures used by a Java virtual machine:

Signature Java type
Z boolean
B byte
C char
S short
I int
J long
F float
D double
L<identifier>; Qualified class identifier
[<type> Array of specified type
(<parameter types>)<result type> Function that returns any value
(<parameter types>)V Method that does not return value

Executing Java Functions

The Java.Invoke or Java.InvokeModule static method is used to execute static Java methods.

Java code:

public class Test {

    public static double staticFunc(double a, double b){

        return (a + b)/2;

    }

}

The Fore code implemented by means of Java.Invoke:

Var
    Result: Variant;
Begin
    
Result := Java.Invoke("Test""staticFunc""(DD)D"1.02.0);

To check Java code for presence of compilation errors, one can use the IJavaUtils.Compile method.

Var
    JUtil: IJavaUtils;
    Result: Variant;
Begin
    JUtil := 
New JavaUtils.Create;
    
Try
        JUtil.Compile(
"c:/Work/Java/src/Test.java");
    
Except On e: Exception Do
        Debug.WriteLine(
"Compilation error: " + e.Message);
    
End Try;
    Result := JUtil.Invoke(
"Test""staticFunc""(DD)D"3.04.0);

Handling Exceptions

All exceptions are handled using the Try…Except…Finally…End Try statement. To handle possible errors that may occur during Java method compilation or execution, use the JavaException class.

For example, change the code of the above displayed function in the following way:

Java code:

public class Test {

    public static double staticFunc(double a, double b, double c){

        if (c==0)

        {

            throw new java.lang.ArithmeticException("Division by zero (parameter c=0)");

        }

        return (a + b)/c;

    }

}

Fore code:

Var
    JUtil: IJavaUtils;
    Result: Variant;
Begin
    JUtil := 
New JavaUtils.Create;
    
Try
        Result := JUtil.Invoke(
"Test""staticFunc""(DDD)D"1.02.00.0);
        Debug.WriteLine(Result);
    Except On e: JavaException Do
        Debug.WriteLine(e.Message);
    
End Try;

This code executes the above displayed function staticFunc with a set of parameters. Code compilation includes handling of possible exceptions using the Try…Except…Finally…End Try statement. If an error occurs, error text is displayed in the development environment console.

See also:

About the Java Assembly