How do I call a specific function of a script?

Category: javax.script, viewed: 1492 time(s).

This code demonstrate the use of Invocable interface to invoke a specific function of a script. The Invocable.invokeFunction() takes the function name with or without a parameter as the function's parameter. The parameter value can be passed as a varargs.

package org.kodejava.example.script;

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

public class InvokingFunction {
    public static void main(String[] args) {
        String script =
            "function sayHello() {" +
            "   sayHello(null);" +
            "}" +
            " " +
            "function sayHello(name) {" +
            "   println('Hi there' + " +
            "       ((name == null) ? '!' : ' ' + name + '!'));" +
            "}";

        ScriptEngineManager manager = new ScriptEngineManager();
        ScriptEngine engine = manager.getEngineByExtension("js");

        try {
            engine.eval(script);

            //
            // Convert / cast the engine into invocable engine.
            //
            Invocable invocableEngine = (Invocable) engine;

            //
            // Invoking sayHello function without parameter.
            //
            invocableEngine.invokeFunction("sayHello");

            //
            // Invoking sayHello function with a parameter.
            //
            invocableEngine.invokeFunction("sayHello", "Jude");
        } catch (ScriptException e) {
            e.printStackTrace();
        } catch (NoSuchMethodException e) {
            e.printStackTrace();
        }
    }
}
Click here to lend your support to: Kode Java Org and make a donation at www.pledgie.com !

 

Can't find what you are looking for? Join our FORUMS and ask some questions!
Download Hundreds of Complimentary Industry Resources

Get hundreds of popular Industry magazines, white papers, webinars, podcasts, and more; all available at no cost to you. With more than 600 complimentary offers, you'll find plenty of titles to suit your professional interests and needs. Click Here and Sign up today!

Sponsored Links

Our Friends

Statistics

Locations of visitors to this page
visitor stats