问题
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