sergey.radov
sergey.radov

Reputation: 134

How can I use custom java type in Graal.js

I have stored a Phone class in a java file and add it to a Static Web project IntelliJ idea. In addition, I created App.js file in the project and tried to call pure node js function under GraalVM using: graalvm/.../node -jvm -polyglot ~/source/graalvm_samples/graal_vm_sample_js/app.js but nodejs under GraalVM fails with the following error: "Access to host class Phone is not allowed or does not exist."

App.js

javascript mixin with JavaCode

console.log("Hello NodeJs");

var Phone = Java.type('graalSample.Phone');

let phone = new Phone(12345);

console.log(phone.number);

console.log(phone.call('Someone'));

Phone class:

package graalSample;

   public class Phone {
    
        public final int number;
    
        public Phone(int number){
    
            this.number = number;
        }
    
        public void call(String name){
    
            System.out.printf("Calling ... "+name);
        }
    }

Sametime, the following code with standard java types works fine. Borrowed from here Use java class in Graal.js

App.js

 var ArrayList = Java.type("java.util.ArrayList");

 var myList = new ArrayList();

 myList.add("hello");

 myList.add("world");

 print(myList);

Upvotes: 1

Views: 1481

Answers (1)

sergey.radov
sergey.radov

Reputation: 134

As turned out, I have missed --jvm.cp parameter and didn't build myClass.java ahead of node run. So, here is a working solution. files in the directory:

./src/graalSample/Phone.java
./src/App.js

The source question had an error in package name either. The package had to be renamed from graal_vm_sample_js to graalSample.

Before running of App.js file, I ran

javac -d ./out/production/graal_vm_sample_js/ ./src/graal/Phone.java

As a result, the class file was created and became available for the Graal.

node --jvm --jvm.cp="/Users/myuser/source/graalvm_samples/graal_vm_sample_js/out/production/graal_vm_sample_js" /Users/myuser/source/graalvm_samples/graal_vm_sample_js/out/production/graal_vm_sample_js/App.js

The output looks like

12345
Calling ...someone

Upvotes: 1

Related Questions