1
2
3
4
5
6
7
8
9
10
11 package org.csveed.bean.conversion;
12
13 import java.lang.reflect.Method;
14
15 import org.csveed.bean.BeanProperty;
16
17
18
19
20 public class BeanWrapper {
21
22
23 private DefaultConverters defaultConverters;
24
25
26 private Object bean;
27
28
29
30
31
32
33
34
35
36 public BeanWrapper(DefaultConverters defaultConverters, Object bean) {
37 this.defaultConverters = defaultConverters;
38 this.bean = bean;
39 }
40
41
42
43
44
45
46
47
48
49
50
51
52 public String getProperty(BeanProperty property) throws ConversionException {
53 Method readMethod = property.getPropertyDescriptor().getReadMethod();
54 Converter converter = getConverter(property);
55 if (converter == null) {
56 throw new NoConverterFoundException("No Converter found for", getPropertyType(property));
57 }
58 try {
59 Object value = readMethod.invoke(bean);
60 return converter.toString(value);
61 } catch (Exception err) {
62 throw new BeanPropertyConversionException("Problem converting", converter.infoOnType(), err);
63 }
64 }
65
66
67
68
69
70
71
72
73
74
75
76
77 public void setProperty(BeanProperty property, String value) throws ConversionException {
78 Method writeMethod = property.getPropertyDescriptor().getWriteMethod();
79 Converter converter = getConverter(property);
80 if (converter == null) {
81 throw new NoConverterFoundException("No Converter found for", getPropertyType(property));
82 }
83 try {
84 writeMethod.invoke(bean, value == null || value.equals("") ? null : converter.fromString(value));
85 } catch (Exception err) {
86 throw new BeanPropertyConversionException("Problem converting", converter.infoOnType(), err);
87 }
88 }
89
90
91
92
93
94
95
96
97
98 protected Converter getConverter(BeanProperty property) {
99 if (property.getConverter() != null) {
100 return property.getConverter();
101 }
102 return defaultConverters.getConverter(getPropertyType(property));
103 }
104
105
106
107
108
109
110
111
112
113 protected Class getPropertyType(BeanProperty property) {
114 return property.getPropertyDescriptor().getPropertyType();
115 }
116
117 }