Shinnara's Blog
Talking with Shinnara :: NaraTalk.com

'script engine'에 해당되는 글 1건

  1. 2009/05/07 Integration Java and Groovy :: Script Engine

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;
}



[MyScript.groovy]
sum = 0;

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"));
       
           
    }

}



Using above, the result is:

Result 65


All works are done successfully.


0 Trackback, 0 Comment

TRACKBACK :: http://naratalk.com/trackback/309 관련글 쓰기

댓글을 달아 주세요

1 
다...... (264)
Computer/Programming (106)
Links (14)
책 읽는 즐거움 (7)
끄적임 (66)
즐거운 과학 나라 (7)
일본 (5)
Study (4)