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
You can refer to the interop guide for a detailed info regarding this.
For your particular case, follow the following steps:
Helloclass and get the built.jarfile.hello).javalibsin your project root directory and copy the.jarfile to it.Your project directory look similar to the following:
Add the following entries to your
Ballerina.tomlfile:Your Ballerina code should look something like the following:
Now you can run this using
ballerina run helloand it should printHello . . .With the
1.2.0release, a new CLI tool calledbindgenwas 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.