01: /*
02: * Created on Oct 25, 2004
03: */
04: package uk.org.ponder.reflect;
05:
06: import java.lang.reflect.Field;
07: import java.util.Iterator;
08: import java.util.Map;
09: import java.util.TreeMap;
10:
11: import uk.org.ponder.stringutil.StringList;
12: import uk.org.ponder.util.UniversalRuntimeException;
13:
14: /**
15: * Automates the process of reflecting a value type full of Strings to and from
16: * a Map of Strings. Useful for HTTP requests and the like. Old-fashioned code,
17: * shortly to be destroyed.
18: *
19: * @author Antranig Basman (antranig@caret.cam.ac.uk)
20: *
21: */
22: public class FieldHash {
23: public TreeMap fieldmap = new TreeMap();
24: private Class target;
25:
26: public FieldHash(Class target) {
27: this .target = target;
28: }
29:
30: public void addField(String fieldname) {
31: Field f = null;
32: try {
33: f = target.getField(fieldname);
34: } catch (Throwable t) {
35: throw UniversalRuntimeException.accumulate(t,
36: "Unable to reflect field " + fieldname
37: + " for class target");
38: }
39: if (f.getType() != String.class) {
40: throw new UniversalRuntimeException(
41: "Only String-typed fields are supported by FieldHash");
42: }
43: fieldmap.put(fieldname, f);
44: }
45:
46: /** Select those fields from the supplied map which match keys stored in
47: * this fieldhash, and set them in the supplied target object. Can deal with
48: * either String[]-valued parameters or String-valued ones.
49: */
50: public void fromMap(Map from, Object targetobj) {
51: for (Iterator keys = from.keySet().iterator(); keys.hasNext();) {
52: String fieldname = (String) keys.next();
53: Field field = (Field) fieldmap.get(fieldname);
54: if (field != null) {
55: Object valueo = from.get(fieldname);
56: String value = valueo instanceof String ? (String) valueo
57: : ((String[]) valueo)[0];
58: try {
59: field.set(targetobj, value);
60: } catch (Throwable t) {
61: throw UniversalRuntimeException.accumulate(t,
62: "Unable to set value of field " + fieldname
63: + " in object " + target);
64: }
65: }
66: }
67:
68: }
69:
70: /** Returns a 2-element array of StringLists, the first holding key names,
71: * the second holding values.
72: */
73: public StringList[] fromObj(Object targetobj) {
74: StringList[] togo = new StringList[2];
75: togo[0] = new StringList();
76: togo[1] = new StringList();
77: try {
78: for (Iterator keys = fieldmap.keySet().iterator(); keys
79: .hasNext();) {
80: String fieldname = (String) keys.next();
81: Field field = (Field) fieldmap.get(fieldname);
82: String value = (String) field.get(targetobj);
83: if (value != null) {
84: togo[0].add(fieldname);
85: togo[1].add(value);
86: }
87: }
88: } catch (Throwable t) {
89: throw UniversalRuntimeException.accumulate(t,
90: "Unable to get value of field");
91: }
92: return togo;
93: }
94: }
|