Java is a very nice and popular programming language. Groovy is a more graceful one. Groovy makes developers feel free. Even I've been on groovy since just about 1 month ago, Groovy makes me very happy and gives many insperations.
Today, I'll show a simple example of "Java and Groovy Integration". Groovy has a "Groovy script engine", so on runtime, SW could behave more dynamically. On my point, I'll apply this feature to support the analysis SW. I make the framework to maintain SW and File In/Out. Other developer and researcher compose the analysis routine using Groovy script.
Today's purpose is getting summation from 1 to the designated number using groovy script and adding sum value from Java Class.
Here are source codes:
[MyClass.java]
public class MyClass {
public int value;
}
public int value;
}
[MyScript.groovy]
sum = 0;
1.upto(number) {
each ->
sum += each
}
sum += myclass.value
1.upto(number) {
each ->
sum += each
}
sum += myclass.value
[ScriptTest.java]
import groovy.lang.*;
import groovy.util.*;
import java.util.*;
public class ScriptTest {
public static void main(String[] args)throws Exception {
MyClass myclass = new MyClass();
myclass.value = 10;
Hashtable<String, Object> variables = new Hashtable<String, Object>();
variables.put("number", new Integer(10));
variables.put("myclass", myclass );
GroovyScriptEngine engine = new GroovyScriptEngine(".");
Binding binding = new Binding(variables);
engine.run("src/MyScript.groovy", binding);
System.out.println("Result "+ binding.getProperty("sum"));
}
}
import groovy.util.*;
import java.util.*;
public class ScriptTest {
public static void main(String[] args)throws Exception {
MyClass myclass = new MyClass();
myclass.value = 10;
Hashtable<String, Object> variables = new Hashtable<String, Object>();
variables.put("number", new Integer(10));
variables.put("myclass", myclass );
GroovyScriptEngine engine = new GroovyScriptEngine(".");
Binding binding = new Binding(variables);
engine.run("src/MyScript.groovy", binding);
System.out.println("Result "+ binding.getProperty("sum"));
}
}
Using above, the result is:
Result 65
All works are done successfully.
댓글을 달아 주세요