interopballerinaballerina-java-interop

How to invoke user defined non-static Java method from Ballerina


The example[1] shows how to invoke a Java method. But in my case I need to invoke my own method from my own class. Something like this

Hello.java

public class Hello {
    public String sayHello() {
        return "Hello . . .";
    }
}

hello_java.bal

import ballerina/io;
import ballerina/java;

function sayHelloJava() returns handle = @java:Method {
    name: "sayHello",
    class: "Hello"
} external;


public function main() {
    var txt = sayHelloJava();
    io:println(txt);
}

When I run, I am getting the following exception

Compiling source
        hello_java.bal
error: .::hello_java.bal:4:1: {ballerina/java}CLASS_NOT_FOUND 'Hello'
Running executables

Error: Could not find or load main class ___init

both the .class and the .bal files are in the same directory

can anyone please tell me the correct syntax to invoke the sayHello java method in ballerina.

Also could you explain more about the handle keyword in ballerina

[1] https://ballerina.io/v1-2/learn/by-example/invoke-java-methods.html


Solution

  • You can refer to the interop guide for a detailed info regarding this.

    For your particular case, follow the following steps:

    With the 1.2.0 release, a new CLI tool called bindgen was introduced to easily generate the Ballerina bindings for Java APIs so the user doesn't have to manually write the bindings as we've done above. Checkout the interop guide I linked to above for more details on it.