01: /*
02: * Copyright 2006 Ethan Nicholas. All rights reserved.
03: * Use is subject to license terms.
04: */
05: package jaxx.types;
06:
07: import jaxx.compiler.*;
08:
09: public class PrimitiveConverter implements TypeConverter {
10: public String getJavaCode(Object object) {
11: if (object instanceof Boolean)
12: return String.valueOf(((Boolean) object).booleanValue());
13: else if (object instanceof Byte)
14: return String.valueOf(((Byte) object).byteValue());
15: else if (object instanceof Short)
16: return String.valueOf(((Short) object).shortValue());
17: else if (object instanceof Integer)
18: return String.valueOf(((Integer) object).intValue());
19: else if (object instanceof Long)
20: return String.valueOf(((Long) object).longValue()) + "L";
21: else if (object instanceof Float)
22: return String.valueOf(((Float) object).floatValue()) + "F";
23: else if (object instanceof Double)
24: return String.valueOf(((Double) object).doubleValue());
25: else if (object instanceof String)
26: return '"' + JAXXCompiler.escapeJavaString((String) object) + '"';
27: else
28: throw new IllegalArgumentException("unsupported object: "
29: + object);
30: }
31:
32: public Object convertFromString(String string, Class type) {
33: if (type == String.class || type == Object.class
34: || type == null)
35: return string;
36: else if (type == int.class || type == Integer.class)
37: return Integer.valueOf(string);
38: else if (type == boolean.class || type == Boolean.class) {
39: if (string.toLowerCase().equals("true"))
40: return Boolean.TRUE;
41: else if (string.toLowerCase().equals("false"))
42: return Boolean.FALSE;
43: else
44: throw new IllegalArgumentException(
45: "expected 'true' or 'false', found '" + string
46: + "'");
47: } else if (type == byte.class || type == Byte.class)
48: return Byte.valueOf(string);
49: else if (type == short.class || type == Short.class)
50: return Short.valueOf(string);
51: else if (type == long.class || type == Long.class)
52: return Long.valueOf(string);
53: else if (type == float.class || type == Float.class)
54: return Float.valueOf(string);
55: else if (type == double.class || type == Double.class)
56: return Double.valueOf(string);
57: else if (type == char.class || type == Character.class) {
58: if (string.length() == 1)
59: return new Character(string.charAt(0));
60: else
61: throw new IllegalArgumentException(
62: "expected a single character, found '" + string
63: + "'");
64: } else
65: throw new IllegalArgumentException("unsupported type: "
66: + type);
67: }
68: }
|