Java Embedded Run Groovy script

Source: Internet
Author: User
Tags getdate groovy script

A. Groovyshell code example1) Simple expression execution, method invocation
/** *  simple answer script execution  *  @throws  Exception */public static void  Evalscripttext ()  throws Exception{//groovy.lang.BindingBinding binding = new  Binding (); Groovyshell shell = new groovyshell (binding); Binding.setvariable ("Name",  "Zhangsan"); Shell.evaluate ("println  ' hello world! i am  '  + name;"); /in script, declare variables, do not use Def, otherwise scrope inconsistent. Shell.evaluate ("date = new date ();");D ate date =  (date) binding.getvariable ("date"); System.out.println ("Date:"  + date.gettime ());//To get the script intrinsic variable value in the return value, or to execute the result//a shell instance, all variable values will be in this " Session "in the" pass. " Date "can get long time =  (Long) shell.evaluate (" Def time = date.gettime () in the script thereafter;  return time; "); System.out.println ("Time:"  + time), binding.setvariable ("list",  new string[]{"A", "B", "C"}) ;//invoke methodstring joinstring =  (String) SHEll.evaluate ("Def call () {return list.join ('  -  ')};call ();"); System.out.println ("Array join:"  + joinstring); shell = null;binding = null;}
2) Pseudo Main method execution.
/** * When groovy scripting is the complete class structure, you can start the script by executing the main method and passing the arguments. */public static void Evalscriptasmainmethod () {string[] args = new string[]{"Zhangsan", "Ten"};//main (string[] args) Binding binding = new binding (args); Groovyshell shell = new Groovyshell (binding); Shell.evaluate ("static void Main (string[] args) {if (args.length! = 2) return ;p rintln (' hello,i am ' + args[0] + ', age ' + args[1]} "); shell = null;binding = null;}
3) Run a groovy script with class structure through the shell
/** *  run full script  *  @throws  Exception */public static void  Evalscripttextfull ()  throws exception{stringbuffer buffer = new stringbuffer (); /define apibuffer.append ("class user{"). Append ("string name;integer age;") . Append ("User (string name,integer age) {this.name = name;this.age = age};"). Append ("String sayhello () {return  ' hello,i am  '  + name +  ',age  '  + age;}} \ n ");//usagebuffer.append (" Def user = new user (name: ' Zhangsan ', age:1); "). Append ("User.sayhello ();"); /groovy.lang.bindingbinding binding = new binding (); Groovyshell shell = new groovyshell (binding); string message =  (String) shell.evaluate (buffer.tostring ()); SYSTEM.OUT.PRINTLN (message);//Override Main method, default execution string mainmethod =  "Static void main ( String[] args) {DEF&NBsp;user = new user (name: ' Lisi ', age:12);p rint (User.sayhello ());} "; Shell.evaluate (Mainmethod); shell = null;}
4) method execution and partial invocation
/** *  Run scripts in a "process" way  *  @throws  Exception */public static void  Evalscript ()  throws exception{ binding binding = new binding ();  Groovyshell shell = new groovyshell (binding);  //Direct method call  //shell.parse (new  File (//))  script script = shell.parse ("Def join" (string[] list)  {return  list.join ('---');} ");  String joinString =  (String) script.invokemethod ("Join",  new string[]{"A1", "B2", "C3"});  system.out.println (joinstring);  ////script can be any format, can be the main method, can also be a normal method  //1)  def  Call () {...}; Call ();  //2)  call () {...};  script = shell.parse ("Static void main (String[] args) {i = i *  2;} ");  script.setproperty ("I",  new integer (Ten));  script.run ();//Run,  SYSTEM.OUT.PRINTLN ( Script.getproperty ("I"));  //the same as sYstem.out.println (Script.getbinding (). getvariable ("I")); script = null; shell =  null;}
Two. Groovyclassloader code example1) Parsing Groovy files
/** * from source file of *.groovy */public static void Parse () throws Exception{groovyclassloader ClassLoader = new Groov Yclassloader (Thread.CurrentThread (). Getcontextclassloader ()); File SourceFile = new file ("D:\\testgroovy.groovy"); Class Testgroovyclass = Classloader.parseclass (new Groovycodesource (sourcefile)); Groovyobject instance = (groovyobject) testgroovyclass.newinstance ();//proxylong time = (Long) Instance.invokemethod (" GetTime ", New Date ()); System.out.println (time);D ate Date = (date) instance.invokemethod ("GetDate", time); System.out.println (Date.gettime ());//hereinstance = Null;testgroovyclass = null;}
2) How to load the compiled groovy file (. Class)
Public static void load ()  throws exception {groovyclassloader classloader  = new groovyclassloader (Thread.CurrentThread (). Getcontextclassloader ()); Bufferedinputstream bis = new bufferedinputstream (New fileinputstream ("D:\\ Testgroovy.class ")); Bytearrayoutputstream bos = new bytearrayoutputstream (); for (;;) {Int i = bis.read (); if ( i == -1) {break;} Bos.write (i);} Class testgroovyclass = classloader.defineclass (Null, bos.tobytearray ());//instance  Of proxy-class//if interface api is in the classpath,you can do  such as://MyObject instance =  (MyObject) testgroovyclass.newinstance () Groovyobject  instance =  (Groovyobject) testgroovyclass.newinstance (); long time =  (Long) instance.invokemethod ("GetTime",  new date ()); System.out.println (time);D ate d ate =  (date) Instance.invokemethod ("GetDate",  time); System.out.println (Date.gettime ());//herebis.close (); Bos.close (); Instance = null;testgroovyclass  = null;}
Three. ScriptEngine1) Pom.xml Dependent
<dependency><groupid>org.codehaus.groovy</groupid><artifactid>groovy</artifactid ><version>2.1.6</version></dependency><dependency><groupId> org.codehaus.groovy</groupid><artifactid>groovy-jsr223</artifactid><version>2.1.6</ Version></dependency>
2) code sample
public static void evalscript ()  throws exception{scriptenginemanager factory = new scriptenginemanager ();// Generate an Engine instance scriptengine engine = factory.getenginebyname ("groovy") every time; System.out.println (Engine.tostring ()); assert engine != null;//javax.script.bindingsbindings  binding = engine.createbindings (); Binding.put ("Date",  new date ());//If the script text is from a file, Please first obtain the contents of the file Engine.eval ("Def gettime () {return date.gettime ();}", binding); Engine.eval ("Def sayhello (Name,age) {return  ' hello,i am  '  + name +  ', age '  + age;} '; long time =  (Long) ((invocable) engine). Invokefunction ("GetTime",  null); System.out.println (time); string message =  (String) ((invocable) engine). Invokefunction ("SayHello",  "Zhangsan", new  integer (12)); SYSTEM.OUT.PRINTLN (message);} 

To be reminded, in groovy, ${expression} will be considered a variable, and if required to output a "$" symbol, it needs to be escaped as "\$".

For more information about ScriptEngine, please refer to. http://shift-alt-ctrl.iteye.com/blog/1896690

Java Embedded Run Groovy script

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.