How to use Nashorn engine to call Java Objects

随声附和 提交于 2021-02-07 12:38:29

问题


I want to use Nashorn console as alternative to Rails c. For example I would like to call Java methods to import data from remote system and to execute data migrations. I found this very intresting:

https://www.baeldung.com/java-nashorn

$JAVA_HOME/bin/jjs
jjs> print("test"); 
test
jjs> 

How I can for example call some Java method from WAR package deployed on Wildfly server and pass some arguments?

Is there any better alternative that you can propose?


回答1:


Refer to Oracle's "Java Scripting Programmer's Guide" chapter 3, "Using Java From Scripts":

To access primitive and reference Java types from JavaScript, call the Java.type() function, which returns a type object that corresponds to the full name of the class passed in as a string. The following example shows you how to get various type objects:

var ArrayList = Java.type("java.util.ArrayList");
var intType = Java.type("int");
var StringArrayType = Java.type("java.lang.String[]");
var int2DArrayType = Java.type("int[][]");

The type object returned by the Java.type() function can be used in JavaScript code similar to how a class name is used in Java. For example, you can can use it to instantiate new objects as follows:

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

Though your question is a bit vague on what exactly you're trying to do. If you're using Nashorn within your application, scripts you execute using it will have access to the Java classes that your application does.




回答2:


From the Nashorn tutorial.

Java:

package com.stackoverflow;
public class Foo {
 public static String bar(String name) {
    System.out.format("Hi there from Java, %s", name);
    return "greetings from java";
 }
}

JavaScript:

var javaFooClazz = Java.type('com.stackoverflow.Foo');
var result =javaFooClazz.bar('John Doe');
print(result);



回答3:


Because nashorn is deprecated with Java 11 I would propose using Groovy as script language. It's similar to java and also supported by the spring framework - for the case that it must not be javascript. Otherwise you should follow discussion in the java area - maybe GraalVM will be the next JavaScript engine for java - also I read that they are working on Nashorn - so the future is undefined here at the moment.



来源:https://stackoverflow.com/questions/52399749/how-to-use-nashorn-engine-to-call-java-objects

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!