Scripting Java (i): Executing scripts in Java

Source: Internet
Author: User
Tags java se

Many implementations of scripting and dynamically typed languages generate Java bytecodes so that programs can is run on t He Java Platform, just as is actual Java programs. Implementing a language in this "or as a Java interpreter class for the scripting language" provides all the advantage S of the Java Platform:scripting implementations can take advantage of the Java platform ' s binary portability, security, and high performance bytecode execution.

The above paragraph is a good answer to why there are so many scripting languages based on the Java platform. Anyway, today we're just going to look at how to execute the scripting language in our Java code. The following two languages are used to demonstrate, Groovy 2.4.0 and Scala 2.11.5.

There are two ways to execute scripts in Java,

Java SE includes JSR 223:scripting for the Java Platform API. This was a framework by which Java applications can "host" script engines. The Scripting framework supports Third-party script engines using the JAR service discovery mechanism. It is possible-drop any JSR-223 compliant script engine in the CLASSPATH and access the same from your Java application S (much like JDBC drivers, JNDI implementations is accessed).

So we can either use the JSR223 API to execute the script or, of course, execute it directly using the API provided by the scripting language. Let's look at the following separately.

JSR-223

by Scriptenginemanager#getenginebyname This API we can get a script engine that implements JSR-223, so how do we know what parameters to get to groovy and Scala's engine? Go in and look at the code, you know.

    Public ScriptEngine Getenginebyname (String shortname) {if (shortname = = null) throw new NullPointerException ()        ;        Look for registered name first Object obj;            if (null! = (obj = Nameassociations.get (shortname))) {Scriptenginefactory SPI = (scriptenginefactory) obj;                try {scriptengine engine = Spi.getscriptengine ();                Engine.setbindings (Getbindings (), scriptcontext.global_scope);            return engine;            } catch (Exception exp) {if (DEBUG) exp.printstacktrace ();            }} for (Scriptenginefactory Spi:enginespis) {list<string> names = null;            try {names = Spi.getnames ();            } catch (Exception exp) {if (DEBUG) exp.printstacktrace (); if (names! = null) {for (String name:names) {if (Shortname.equals (name) ) {Try {ScriptEngine engine = Spi.getscriptengine ();                            Engine.setbindings (Getbindings (), scriptcontext.global_scope);                        return engine;                        } catch (Exception exp) {if (DEBUG) exp.printstacktrace ();    }}}}} return null; }
    /**     * Registers a <code>ScriptEngineFactory</code> to handle a language     * name.  Overrides Any such association found using the Discovery mechanism.     * @param name the name to being associated with the <code>scriptenginefactory</code>.     * @param factory The class to associate with the given name.     * @throws NullPointerException If any of the parameters is null.     */Public    void Registerenginename (String name, Scriptenginefactory Factory) {        if (name = = NULL | | factory = = NULL) throw new NullPointerException ();        Nameassociations.put (name, Factory);    }

So you can see that there are two ways to find ScriptEngine,

    • If you have already registered a name by calling Scriptenginemanager#registerenginename , you need to know what name is registered;
    • If not, then you need to know the specific scriptenginefactory implementation of the GetNames method returned what;

Scriptenginefactory is loaded through the serviceloader mechanism to see what groovy and Scala are all about,


The contents of the Javax.script.ScriptEngineFactory file are, respectively,

Org.codehaus.groovy.jsr223.GroovyScriptEngineFactory
Scala.tools.nsc.interpreter.imain$factory

Did not find the call Registerenginename method, then look at the respective GetNames method, Groovyscriptenginefactory,

    private static final String short_name = "Groovy";    private static final String language_name = "Groovy";
    static {        list<string> n = new arraylist<string> (2);        N.add (short_name);        N.add (language_name);        NAMES = Collections.unmodifiablelist (n);        n = new arraylist<string> (1);        N.add ("Groovy");        EXTENSIONS = Collections.unmodifiablelist (n);        n = new arraylist<string> (1);        N.add ("Application/x-groovy");        Mime_types = Collections.unmodifiablelist (n);    }

So you can get groovy's scriptengine by "groovy" or "groovy". Look at the Imain,

    @BeanProperty    val names:jlist[string] = asjavalist ("Scala")

Alright, that's through "Scala" to get it. The code is on the back, two ways together.

Shell

Scripts can be executed directly through both Groovy.lang.GroovyShell and Imain, both of which are the APIs provided by the scripting language described above.

We can try it out in the shell environment provided by the scripting language,

$ sudo groovy/bin/groovysh[sudo] password for Blues:feb 3, 12:36:43 AM Org.codehaus. Groovy.runtime.m12n.MetaInfExtensionModule Newmodulewarning:module [Groovy-nio]-Unable to load extension class [ Org.codehaus.groovy.runtime.niogroovymethods]groovy Shell (2.4.0, jvm:1.6.0_33) Type ': Help ' or ': H ' for Help.-----------------------------------------------------------------------------groovy:000> Import groovy.lang.groovyshell===> groovy.lang.groovyshellgroovy:000> Groovysh = new GroovyShell () ===> [email  protected]groovy:000> groovysh.evaluate ("Import java.util.Random; Random = new Random (); Random.nextint (); ") ===> -1378717507 
$ scalawelcome to Scala version 2.11.5 (Java HotSpot (TM) 64-bit Server VM, Java 1.7.0_51). Type in expressions to has them evaluated. Type:help for more information.scala> import Scala.tools.nsc.interpreter._import scala.tools.nsc.interpreter._ scala> val imain = new Imain () IMain:scala.tools.nsc.interpreter.IMain = [email protected]scala> imain.eval (" Import Java.util.Random; Val random = new Random (); Random.nextint (); ") Res0:object = 1320282527

There's no problem.

Finally, back to the beginning of the question, how to execute the script in Java code? Here are two ways to paste the code together,

import groovy.lang.groovyshell;import Scala.tools.nsc.interpreter.imain;import  Javax.script.scriptengine;import Javax.script.scriptenginemanager;public class Main {public static void Main (string[]        args) throws Exception {Scriptenginemanager sem = new Scriptenginemanager (); String Script_groovy = "Import java.util.Random; Random = new Random ();        Random.nextint (); ";        ScriptEngine Se_groovy = Sem.getenginebyname ("Groovy");        System.out.println (Se_groovy.eval (Script_groovy));        Groovyshell Groovyshell = new Groovyshell ();        System.out.println (Groovyshell.evaluate (Script_groovy)); String Script_scala = "Import java.util.Random; Val random = new Random ();        Random.nextint (); ";        ScriptEngine Se_scala = Sem.getenginebyname ("Scala");        System.out.println (Se_scala.eval (Script_scala));        Imain Imain = new Imain ();    System.out.println (Imain.eval (Script_scala)); }}
142472532416912552974593273951109624277

Originally wanted to play under the JDK's own JSR223 implementation, that is Nashorn, which are animplementationof the ECMAScript Edition 5.1 Language specification, But to JDK8 to have to play, another time ^_^ Pat.

Resources
    • http://docs.oracle.com/javase/8/docs/technotes/guides/scripting/

Scripting Java (i): Executing scripts in Java

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.