ognlによるデータの初期化(mapセットlist|map)

3469 ワード

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();
			else
				return 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 + "[";
			else
				prefix = currentNode.jjtGetParent() + "[";
			if (fullExp.startsWith(prefix))
				currentObj = new MyList();
			else
				currentObj = 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 {
			@Override
			public Object get(int index) {
				try {
					return super.get(index);
				} catch (Exception e) {
					return null;
				}
			}
		}

	}

 
@Test
	public 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}}}}}}