View Javadoc
1   package org.csveed.bean.conversion;
2   
3   import java.lang.reflect.Method;
4   
5   import org.csveed.bean.BeanProperty;
6   
7   public class BeanWrapper {
8   
9       private DefaultConverters defaultConverters;
10  
11      private Object bean;
12  
13      public BeanWrapper(DefaultConverters defaultConverters, Object bean) {
14          this.defaultConverters = defaultConverters;
15          this.bean = bean;
16      }
17  
18      public String getProperty(BeanProperty property) throws ConversionException {
19          Method readMethod = property.getPropertyDescriptor().getReadMethod();
20          Converter converter = getConverter(property);
21          if (converter == null) {
22              throw new NoConverterFoundException("No Converter found for", getPropertyType(property));
23          }
24          try {
25              Object value = readMethod.invoke(bean);
26              return converter.toString(value);
27          } catch (Exception err) {
28              throw new BeanPropertyConversionException("Problem converting", converter.infoOnType(), err);
29          }
30      }
31  
32      public void setProperty(BeanProperty property, String value) throws ConversionException {
33          Method writeMethod = property.getPropertyDescriptor().getWriteMethod();
34          Converter converter = getConverter(property);
35          if (converter == null) {
36              throw new NoConverterFoundException("No Converter found for", getPropertyType(property));
37          }
38          try {
39              writeMethod.invoke(bean, value == null || value.equals("") ? null : converter.fromString(value));
40          } catch (Exception err) {
41              throw new BeanPropertyConversionException("Problem converting", converter.infoOnType(), err);
42          }
43      }
44  
45      protected Converter getConverter(BeanProperty property) {
46          if (property.getConverter() != null) {
47              return property.getConverter();
48          }
49          return defaultConverters.getConverter(getPropertyType(property));
50      }
51  
52      protected Class getPropertyType(BeanProperty property) {
53          return property.getPropertyDescriptor().getPropertyType();
54      }
55  
56  }