Path: blob/aarch64-shenandoah-jdk8u272-b10/nashorn/samples/engine/callmethod.js
32284 views
#// Usage: jjs -scripting callmethod.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 calling a script object34// method from script engine user code3536var 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 = {46func: function() {47print("I am func of " + this);48},4950toString: function() {51return "Object 'obj'";52}53};54CODE);5556// invoke methods of an object in script world57// from javax.script.Invocable interface. But, hey,58// calling code is JavaScript and don't worry about types :)5960// get that script object on which to call a method61var scriptObj = engine.get("obj");62// call 'func' method on object 'obj'63engine.invokeMethod(scriptObj, "func");646566