Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Embedding a JavaScript snippet in a Java class method

I have a java program that opens, reads, and write multiple files. it also contains complex logic formatting.

Now I wrote on jsfiddle an easy javascript here to do some tree traversals and parsing for me, and it is much easier than implement in Java.

My challenge now is how can i “embed” this Javascript script into my Java method. I’m primarily a Java coder.

The pseudocode for the Java method is something like this:

<Java method begins……>

      String input = “ABC”  //its more complex than ABC
      String o1= null;
         //JavaScript script begins,
             //Javascript evaluates the Java string input
             //Javascript output is assigned to Java o1
               o1 =  output;
        //Javascript script ends 

    //maniputate and process Java string o1 - which is not null
<Java method ends>
like image 773
bouncingHippo Avatar asked Aug 24 '26 00:08

bouncingHippo


1 Answers

Fairly simple to do with Java 8. You can use Nashorn.

import javax.script.Invocable;
import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;

public class JsTest {

  @org.junit.Test
  public void test() throws Exception  {
    ScriptEngine jsEngine = new ScriptEngineManager().getEngineByName("nashorn");
    jsEngine.eval("var say = function(name) {return 'Hello ' + name;}");

    Invocable jsScript = (Invocable) jsEngine;

    Object result = jsScript.invokeFunction("say", "XYZ");
    System.out.println(result);
  }
}

The eval method has various possible parameters. It would also be possible, loading the script from a file.

A good tutorial can be found here: http://winterbe.com/posts/2014/04/05/java8-nashorn-tutorial

like image 188
spa Avatar answered Aug 26 '26 16:08

spa