Need to add Groovy-2.4.3.jar to Classpath
One: Execute groovy code in Java with Groovyclassloader
Calculatemax.groovy
1 class calculatemax{2 def Integer getmax (List values) {3 Values.max (); 4 }5 }
View Code
Usegroovyclassloader.java
1 Packagegroovy_java_1;2 3 ImportJava.io.File;4 Importjava.util.ArrayList;5 6 ImportGroovy.lang.GroovyClassLoader;7 ImportGroovy.lang.GroovyObject;8 9 Public classUsegroovyclassloader {Ten Public Static voidMain (string[] args) { OneGroovyclassloader loader =NewGroovyclassloader (); A Try{ -class<?> Groovyclass = Loader.parseclass (NewFile ("Src/groovy_java_1/calculatemax.groovy")); -Groovyobject Groovyobject =(Groovyobject) groovyclass.newinstance (); thearraylist<integer> numbers =NewArraylist<integer>(); -Numbers.add (NewInteger (1)); -Numbers.add (NewInteger (10)); -object[] arguments ={numbers}; +Object value = Groovyobject.invokemethod ("Getmax", arguments); - assertValue.equals (NewInteger (10)); + System.out.println (value); A}Catch(Exception e) { at e.printstacktrace (); - } - } - -}
View Code
Two: Execute groovy code in Java with Groovyshell
Usegroovyshell.java
1 PackageGroovy_java_0;2 3 ImportJava.math.BigDecimal;4 5 Importgroovy.lang.Binding;6 ImportGroovy.lang.GroovyShell;7 8 Public classUsegroovyshell {9 Public Static voidMain (string[] args) {TenBinding binding =NewBinding (); OneBinding.setvariable ("X", 2.4); ABinding.setvariable ("Y", 8); -Groovyshell Shell =NewGroovyshell (binding); -Object value = shell.evaluate ("X+y"); the assertValue.equals (NewBigDecimal (10.4)); - } - -}
View Code
Three: Execute groovy code in Java with Groovyscriptengine
Hello.groovy
1 def hellostatement = "Hello ${name}"
View Code
Usegroovyscriptengine.java
1 Packagegroovy_java_2;2 3 Importgroovy.lang.Binding;4 ImportGroovy.util.GroovyScriptEngine;5 6 Public classUsegroovyscriptengine {7 Public Static voidMain (string[] args) {8 Try {9String[] Roots =Newstring[]{"src/groovy_java_2"};//Setting the root directoryTenGroovyscriptengine GSE =NewGroovyscriptengine (roots);//Initialize engine One ABinding binding =NewBinding (); -Binding.setvariable ("name", "Gweneth"); - theObject output = Gse.run ("Hello.groovy", binding); - System.out.println (output); - assertOutput.equals ("Hello Gweneth"); - +}Catch(Exception e) { - //Todo:handle Exception + e.printstacktrace (); A } at } - -}
View Code
Calling Groovy from Java