27 * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING |
27 * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING |
28 * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS |
28 * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS |
29 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. |
29 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. |
30 */ |
30 */ |
31 |
31 |
32 import javax.script.*; |
32 import javax.script.Invocable; |
|
33 import javax.script.ScriptEngine; |
|
34 import javax.script.ScriptEngineManager; |
33 |
35 |
|
36 @SuppressWarnings("javadoc") |
34 public class RunnableImplObject { |
37 public class RunnableImplObject { |
35 public static void main(String[] args) throws Exception { |
38 public static void main(final String[] args) throws Exception { |
36 ScriptEngineManager manager = new ScriptEngineManager(); |
39 final ScriptEngineManager manager = new ScriptEngineManager(); |
37 ScriptEngine engine = manager.getEngineByName("nashorn"); |
40 final ScriptEngine engine = manager.getEngineByName("nashorn"); |
38 |
41 |
39 // JavaScript code in a String |
42 // JavaScript code in a String |
40 String script = "var obj = new Object(); obj.run = function() { print('run method called'); }"; |
43 final String script = "var obj = new Object(); obj.run = function() { print('run method called'); }"; |
41 |
44 |
42 // evaluate script |
45 // evaluate script |
43 engine.eval(script); |
46 engine.eval(script); |
44 |
47 |
45 // get script object on which we want to implement the interface with |
48 // get script object on which we want to implement the interface with |
46 Object obj = engine.get("obj"); |
49 final Object obj = engine.get("obj"); |
47 |
50 |
48 Invocable inv = (Invocable) engine; |
51 final Invocable inv = (Invocable) engine; |
49 |
52 |
50 // get Runnable interface object from engine. This interface methods |
53 // get Runnable interface object from engine. This interface methods |
51 // are implemented by script methods of object 'obj' |
54 // are implemented by script methods of object 'obj' |
52 Runnable r = inv.getInterface(obj, Runnable.class); |
55 final Runnable r = inv.getInterface(obj, Runnable.class); |
53 |
56 |
54 // start a new thread that runs the script implemented |
57 // start a new thread that runs the script implemented |
55 // runnable interface |
58 // runnable interface |
56 Thread th = new Thread(r); |
59 final Thread th = new Thread(r); |
57 th.start(); |
60 th.start(); |
58 th.join(); |
61 th.join(); |
59 } |
62 } |
60 } |
63 } |