からjarをダウンロードしてクラスパスに追加。
使い方を試すために、簡単なテストを書いてみた。
プロパティの取得・設定・staticメソッドの呼び出し・配列・マップあたりが出来れば一通りOKかな。
package org.okazuki.ognl.sample; import java.util.HashMap; import java.util.List; import java.util.Map; import junit.framework.TestCase; import ognl.Ognl; import ognl.OgnlContext; public class OgnlTest extends TestCase { private OgnlContext context; private Data data; protected void setUp() throws Exception { super.setUp(); context = new OgnlContext(); data = new Data(); context.put("data", data); } protected void tearDown() throws Exception { super.tearDown(); context = null; } public void testGetValue() throws Exception { final String expression = "data.value"; Object parseExpression = Ognl.parseExpression(expression); assertEquals(new Integer(0), Ognl.getValue(parseExpression, context)); data.setValue(100); assertEquals(new Integer(100), Ognl.getValue(parseExpression, context)); } public void testSetValue() throws Exception { final String expression = "data.value"; Object parseExpression = Ognl.parseExpression(expression); Ognl.setValue(parseExpression, context, new Integer(10)); assertEquals(10, data.getValue()); } public void testStaticMethod() throws Exception { final String expression = "@org.okazuki.ognl.sample.Data@foo()"; Object parseExpression = Ognl.parseExpression(expression); assertEquals("Hello world", Ognl.getValue(parseExpression, context)); } public void testArray() throws Exception { final String expression = "new int[]{1, 2, 3}"; Object parseExpression = Ognl.parseExpression(expression); int[] ret = (int[]) Ognl.getValue(parseExpression, context); assertEquals(3, ret.length); assertEquals(1, ret[0]); assertEquals(2, ret[1]); assertEquals(3, ret[2]); } public void testList() throws Exception { final String expression = "{1, 2, 3}"; Object parseExpression = Ognl.parseExpression(expression); List ret = (List) Ognl.getValue(parseExpression, context); assertEquals(3, ret.size()); assertEquals(new Integer(1), ret.get(0)); assertEquals(new Integer(2), ret.get(1)); assertEquals(new Integer(3), ret.get(2)); } public void testMap() throws Exception { final String expression = "#{\"name\" : \"tarou\", \"age\" : 18}"; Object parseExpression = Ognl.parseExpression(expression); Map value = (Map) Ognl.getValue(parseExpression, context); assertEquals("tarou", value.get("name")); assertEquals(new Integer(18), value.get("age")); } // マップに対してもプロパティちっくにアクセスできる! public void testMap2() throws Exception { Map map = new HashMap(); map.put("hoge", "hage"); context.put("map", map); final String expression = "map.hoge"; Object parseExpression = Ognl.parseExpression(expression); assertEquals("hage", Ognl.getValue(parseExpression, context)); } } class Data { private int value; public int getValue() { return value; } public void setValue(int value) { this.value = value; } // static method public static String foo() { return "Hello world"; } }
最後のテストの奴がちょっとびっくり。