Path: blob/aarch64-shenandoah-jdk8u272-b10/nashorn/samples/engine/interface.js
32284 views
#// Usage: jjs -scripting interface.js12/*3* Copyright (c) 2014, Oracle and/or its affiliates. All rights reserved.4*5* Redistribution and use in source and binary forms, with or without6* modification, are permitted provided that the following conditions7* are met:8*9* - Redistributions of source code must retain the above copyright10* notice, this list of conditions and the following disclaimer.11*12* - Redistributions in binary form must reproduce the above copyright13* notice, this list of conditions and the following disclaimer in the14* documentation and/or other materials provided with the distribution.15*16* - Neither the name of Oracle nor the names of its17* contributors may be used to endorse or promote products derived18* from this software without specific prior written permission.19*20* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS21* IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,22* THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR23* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR24* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,25* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,26* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR27* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF28* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING29* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS30* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.31*/3233// Example demonstrating how to implement a Java interface34// whose methods are backed by global script functions3536var ScriptEngineManager = Java.type("javax.script.ScriptEngineManager");37// create manager38var manager = new ScriptEngineManager();39// create engine40var engine = manager.getEngineByName("js");4142// eval code - too many script escapes?43// use heredoc !44engine.eval(<<CODE45function run() {46print("run global function called");47}48CODE);4950// create Java interface object whose methods are51// implemented by script functions. This is from52// javax.script.Invocable. But we are in JS world,53// don't worry about types :)5455var Runnable = Java.type("java.lang.Runnable");56var r = engine.getInterface(Runnable.class);57print(r.class);5859r.run();606162