vendredi 29 avril 2022

Calling Java from Node.js

I'm trying to follow this simple tutorial about calling Java from Node.js:

My test script:

var java = require('java');
var javaLangSystem = java.import('java.lang.System');

javaLangSystem.out.printlnSync('Hello Java!');

Here is the console:

$ npm init
This utility will walk you through creating a package.json file.
It only covers the most common items, and tries to guess sensible defaults.
...
$ npm install java

added 18 packages, and audited 19 packages in 11s

1 package is looking for funding
  run `npm fund` for details

2 high severity vulnerabilities

To address all issues, run:
  npm audit fix

Run `npm audit` for details.
$ node test.js 
/home/Projects/test-java/node_modules/java/lib/nodeJavaBridge.js:240
  var fields = SyncCall(clazz, 'getDeclaredFields')();
                                                   ^

Error: Error running instance method
java.lang.NullPointerException
    at java.base/java.util.Objects.requireNonNull(Objects.java:208)
    at java.base/java.lang.invoke.MethodHandleImpl$1.reflectiveInvoker(MethodHandleImpl.java:1660)
    at java.base/jdk.internal.reflect.DirectMethodHandleAccessor.invoke(DirectMethodHandleAccessor.java:131)
    at java.base/java.lang.reflect.Method.invoke(Method.java:577)

    at Java.java.import (/home/Projects/test-java/node_modules/java/lib/nodeJavaBridge.js:240:52)
    at Object.<anonymous> (/home/Projects/test-java/test.js:2:33)
    at Module._compile (node:internal/modules/cjs/loader:1103:14)
    at Object.Module._extensions..js (node:internal/modules/cjs/loader:1157:10)
    at Module.load (node:internal/modules/cjs/loader:981:32)
    at Function.Module._load (node:internal/modules/cjs/loader:822:12)
    at Function.executeUserEntryPoint [as runMain] (node:internal/modules/run_main:77:12)
    at node:internal/main/run_main_module:17:47 {
  cause: nodeJava_java_lang_NullPointerException {}
}
$ java --version
java 18.0.1 2022-04-19
Java(TM) SE Runtime Environment (build 18.0.1+10-24)
Java HotSpot(TM) 64-Bit Server VM (build 18.0.1+10-24, mixed mode, sharing)

What may be going wrong here?

I've tried to debug it and it seems that obj[syncMethodName].bind(obj) throws a java.lang.NullPointerException at java.base/java.lang.reflect.Method.invoke(Method.java:577) when

obj == class java.lang.System
syncMethodName == 'getDeclaredFieldsSync'




Aucun commentaire:

Enregistrer un commentaire