01: /*
02: * Created on Oct 26, 2004
03: */
04: package uk.org.ponder.conversion;
05:
06: import java.lang.reflect.Constructor;
07: import java.lang.reflect.Method;
08:
09: import uk.org.ponder.saxalizer.SAXAccessMethod;
10: import uk.org.ponder.util.UniversalRuntimeException;
11:
12: /**
13: * A default SAXLeafTypeParser capable of dealing with any object declaring
14: * a toString() method and a constructor accepting a single String argument.
15: * @author Antranig Basman (antranig@caret.cam.ac.uk)
16: */
17: // TODO: Is this ancient and inefficient piece of cruft used anywhere?
18: // Why precisely did we invent it?
19: public class StringableLeafTypeParser implements LeafObjectParser {
20: private Constructor stringcons;
21: private Method tostring;
22:
23: public StringableLeafTypeParser(Constructor stringcons,
24: Method tostring) {
25: this .stringcons = stringcons;
26: this .tostring = tostring;
27: }
28:
29: public static StringableLeafTypeParser checkClass(Class clazz) {
30: StringableLeafTypeParser togo = null;
31: Constructor[] constructors = clazz.getConstructors();
32: Constructor stringcons = null;
33: for (int i = 0; i < constructors.length; ++i) {
34: Constructor cons = constructors[i];
35: Class[] params = cons.getParameterTypes();
36: if (params.length == 1 && params[0] == String.class) {
37: stringcons = cons;
38: }
39: }
40: Method tostring = null;
41: try {
42: tostring = clazz.getMethod("toString",
43: SAXAccessMethod.emptyclazz);
44: if (tostring.getDeclaringClass() == Object.class) {
45: tostring = null;
46: }
47: } catch (Throwable t) {
48: }
49: if (stringcons != null && tostring != null) {
50: togo = new StringableLeafTypeParser(stringcons, tostring);
51: }
52: return togo;
53: }
54:
55: public Object parse(String toparse) {
56: try {
57: return stringcons.newInstance(new Object[] { toparse });
58: } catch (Throwable t) {
59: throw UniversalRuntimeException.accumulate(t,
60: "Error invoking default constructor for object of type "
61: + stringcons.getDeclaringClass());
62: }
63: }
64:
65: public String render(Object torender) {
66: try {
67: return tostring.invoke(torender, SAXAccessMethod.emptyobj)
68: .toString();
69: } catch (Throwable t) {
70: throw UniversalRuntimeException.accumulate(t,
71: "Error invoking toString method for object of type "
72: + tostring.getDeclaringClass());
73: }
74: }
75:
76: //NB - probably wrong.
77: public Object copy(Object tocopy) {
78: return tocopy;
79: }
80:
81: }
|