首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 开发语言 > 编程 >

利用ognl 初始化数据(地图 套list|地图)

2013-07-29 
利用ognl 初始化数据(map 套list|map)public static class MyNullHandler implements NullHandler {@Suppr

利用ognl 初始化数据(map 套list|map)
public static class MyNullHandler implements NullHandler {@SuppressWarnings("rawtypes")public Object nullMethodResult(Map context, Object target,String methodName, Object[] args) {System.err.println("==");return null;}public String getFullExp(Node node) {if (node.jjtGetParent() == null)return node.toString();elsereturn getFullExp(node.jjtGetParent());}@SuppressWarnings({ "rawtypes", "unchecked" })public Object nullPropertyValue(Map context, Object target,Object property) {Object currentObj = null;OgnlContext ctx = (OgnlContext) context;ASTProperty currentNode = (ASTProperty) ((ASTConst) ctx.getCurrentNode()).jjtGetParent();String fullExp = getFullExp(currentNode);String prefix = "";if (isFirstNode(currentNode))prefix = currentNode + "[";elseprefix = currentNode.jjtGetParent() + "[";if (fullExp.startsWith(prefix))currentObj = new MyList();elsecurrentObj = new HashMap();if (target instanceof HashMap) {((HashMap) target).put(property, currentObj);}if (target instanceof List) {((List) target).add((Integer) property, currentObj);}return currentObj;}class MyList extends ArrayList {@Overridepublic Object get(int index) {try {return super.get(index);} catch (Exception e) {return null;}}}}

?

@Testpublic void testAutoCreateMapAndList() {try {final OgnlExpressionEvaluator ee = new OgnlExpressionEvaluator();OgnlRuntime.setNullHandler(Object.class, new MyNullHandler());Map<String, Object> root = new HashMap<String, Object>();ee.setValue(root, root, "root.bar[0].name", "mike", true);ee.setValue(root, root, "root.bar[0].id", "001", true);// 手动初始化// List list = (List) ((Map) root.get("root")).get("bar");// Map m = new HashMap();// list.add(1, m);// m.put("name", "hzl");// m.put("id", "003");ee.setValue(root, root, "root.bar[1].name", "lizhs", true);ee.setValue(root, root, "root.bar[1].id", "002", true); ee.setValue(root, root, "root.bar[1].dep[0][0].name", "研发部门", true);ee.setValue(root, root, "root.bar[1].dep[0][1].name", "测试部门", true);ee.setValue(root, root, "root.bar[1].dep[1][0].name", "研发部门2", true);ee.setValue(root, root, "root.bar[1].dep[1][1].name", "测试部门2", true);// Object findValue = ee.findValue("a.b.c", root,// root);// System.out.println(findValue);System.out.println(root);} catch (Exception e) {e.printStackTrace();}}

?

{root={bar=[{id=001, name=mike}, {id=002, name=lizhs, dep=[[{name=研发部门}, {name=测试部门}], [{name=研发部门2}, {name=测试部门2}]]}]}}

?

热点排行