我正在使用GraalVM与JavaScript进行互操作,因为Nashorn is due to be deprecated。
问题是我的变量在JavaScript运行时中是undefined
。
ScriptEngine engine = new ScriptEngineManager().getEngineByName("graal.js");
String path = "rules.js";
InputStream is = Main.class.getClassLoader().getResourceAsStream(path);
Reader reader = new InputStreamReader(is);
engine.eval(reader);
Invocable inv = (Invocable) engine;
Object obj = engine.get("obj");
User user = new User();
user.setName("username");
user.setProfile("admin");
Boolean value = (Boolean) inv.invokeMethod(obj, "validatePermission", user);
这是我正在运行的JavaScript代码:
var obj = new Object();
obj.validatePermission = function(user) {
console.log(user.profile)
if(user.profile === 'admin') {
return true;
} else {
throw 'Unauthorized. User must be administrator.';
}
}
POM依赖项:
<project>
<properties>
<graalvm.version>19.0.0</graalvm.version>
</properties>
<dependencies>
<dependency>
<groupId>org.graalvm.js</groupId>
<artifactId>js</artifactId>
<version>${graalvm.version}</version>
</dependency>
<dependency>
<groupId>org.graalvm.js</groupId>
<artifactId>js-scriptengine</artifactId>
<version>${graalvm.version}</version>
</dependency>
<dependency>
<groupId>org.graalvm.truffle</groupId>
<artifactId>truffle-api</artifactId>
<version>${graalvm.version}</version>
</dependency>
</dependencies>
</project>
答案 0 :(得分:0)
设置Nashorn兼容模式即可解决。
System.setProperty("polyglot.js.nashorn-compat", "true");
有关此处的更多信息:Nashorn Migration Guide。
以上所有信息均由GraalVM团队提供this issue。