Peter Penzov
Peter Penzov

Reputation: 1648

How to use Nashorn engine to call Java Objects

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?

Upvotes: 9

Views: 5702

Answers (3)

PowerStat
PowerStat

Reputation: 3821

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.

Upvotes: 0

user65839
user65839

Reputation:

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.

Upvotes: 4

Victor Gubin
Victor Gubin

Reputation: 2937

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);

Upvotes: 3

Related Questions