1 package net.sourceforge.jparam.parser;
2
3 import java.lang.reflect.Constructor;
4 import java.util.HashMap;
5 import java.util.Iterator;
6 import java.util.List;
7 import java.util.Map;
8
9 import net.sourceforge.jparam.JParamException;
10 import net.sourceforge.jparam.conversion.ConverterRegistry;
11 import net.sourceforge.jparam.conversion.weights.ScalarConversionWeight;
12
13 /***
14 * A description of class MapLeaf
15 */
16 public class MapLeaf implements TreeNode {
17 private List items;
18
19 /***
20 * Create a new MapLeaf object, with the given MapItems as items
21 */
22 public MapLeaf(List items) {
23 this.items = items;
24 }
25
26 public Object getConstructedValue(Class expectedType)
27 throws JParamException {
28 Map map;
29
30 if (Map.class.isAssignableFrom(expectedType)){
31 try{
32 Constructor emptyConstructor = expectedType.getConstructor(new Class[]{});
33 map = (Map)emptyConstructor.newInstance(new Object[]{});
34 } catch (Exception e){
35 throw new JParamException("Expected type is a map subclass with no empty constructor, cannot create a map of this type: " + expectedType.getName());
36 }
37 } else {
38 map = new HashMap();
39 }
40
41 Iterator itr = items.iterator();
42
43 while (itr.hasNext()) {
44 MapItem item = (MapItem) itr.next();
45
46 Object key = item.getKey().getConstructedValue(Object.class);
47 Object value = item.getValue().getConstructedValue(Object.class);
48 map.put(key, value);
49 }
50 return map;
51 }
52
53 public String toString() {
54 StringBuffer res = new StringBuffer("MapLeaf, items={");
55 boolean isFirst = true;
56
57 Iterator itr = items.iterator();
58 while (itr.hasNext()) {
59 if (isFirst) {
60 isFirst = false;
61 } else {
62 res.append(" ,");
63 }
64 res.append(itr.next().toString());
65 }
66 res.append('}');
67 return res.toString();
68 }
69
70 public ScalarConversionWeight getConversionWeight(Class expectedClass) {
71 return ConverterRegistry.getInstance().getConversionWeight(
72 HashMap.class, expectedClass);
73 }
74 }