Path: blob/aarch64-shenandoah-jdk8u272-b10/nashorn/samples/engine/interface2.js
32284 views
#// Usage: jjs -scripting interface2.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// Simple example demonstrating how to implement java interface34// whose methods are backed by script methods of a script object3536var 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(<<CODE45var obj = {46run: function() {47print("I am run method of 'obj'");48}49};50CODE);5152// create Java interface object whose methods are53// implemented by script methods of a script object54// This is from javax.script.Invocable. But we are55// in JS world, don't worry about types :)5657var Runnable = Java.type("java.lang.Runnable");5859var scriptObj = engine.get("obj");60var r = engine.getInterface(scriptObj, Runnable.class);61print(r.class);62r.run();636465