組み込んで動的にクラス生成

スクリプトがこんな感じで。


class MyHashMap extends HashMap {}

m1 = new MyHashMap()
m1.put('aaa', 'bbb')

def m2 = new MyHashMap()

Javaのコードがこんな感じで。


public class Main {

public static void main(String[] args) throws IOException {
Binding binding = new Binding();
GroovyShell shell = new GroovyShell(binding);

shell.evaluate(new File("foo.groovy"));

System.out.println(binding.getVariables());
HashMap m1 = (HashMap) binding.getVariable("m1");
m1.put("ccc", "ddd");
System.out.println(m1);
}

}

実行結果がこう…っと。


{m1={aaa=bbb}}
{ccc=ddd, aaa=bbb}

やっぱり遅い気もするけど、動的なクラス生成はいいなぁ。