1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22 package org.nuiton.decorator;
23
24 import org.apache.commons.beanutils.PropertyUtils;
25 import org.apache.commons.logging.Log;
26 import org.apache.commons.logging.LogFactory;
27
28 import java.beans.PropertyDescriptor;
29 import java.lang.reflect.Method;
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47 public class PropertyDecorator<O> extends Decorator<O> {
48
49 private static final long serialVersionUID = 1L;
50
51
52 static private final Log log = LogFactory.getLog(PropertyDecorator.class);
53
54
55 protected String property;
56
57 protected transient Method m;
58
59 @Override
60 public String toString(Object bean) {
61 try {
62 return getM().invoke(bean) + "";
63 } catch (Exception e) {
64 log.error("could not convert for reason : " + e, e);
65 return "";
66 }
67 }
68
69 public String getProperty() {
70 return property;
71 }
72
73 protected PropertyDecorator(Class<O> internalClass,
74 String property) throws NullPointerException {
75 super(internalClass);
76 if (property == null) {
77 throw new NullPointerException("property can not be null.");
78 }
79 this.property = property;
80
81 getM();
82 }
83
84 protected Method getM() {
85 if (m == null) {
86 for (PropertyDescriptor propertyDescriptor : PropertyUtils.getPropertyDescriptors(getType())) {
87 if (propertyDescriptor.getName().equals(property)) {
88 m = propertyDescriptor.getReadMethod();
89 break;
90 }
91 }
92 if (m == null) {
93 throw new IllegalArgumentException("could not find the property " + property + " in " + getType());
94 }
95 }
96 return m;
97 }
98 }