KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > jodd > bean > BeanPropertyUtil


1 // Copyright (c) 2003-2007, Jodd Team (jodd.sf.net). All Rights Reserved.
2

3 package jodd.bean;
4
5 import jodd.typeconverter.TypeConverter;
6 import jodd.typeconverter.TypeConverterManager;
7 import jodd.util.ReflectUtil;
8
9 import java.lang.reflect.Method JavaDoc;
10 import java.lang.reflect.InvocationTargetException JavaDoc;
11 import java.lang.reflect.Array JavaDoc;
12 import java.lang.reflect.Field JavaDoc;
13 import java.util.HashMap JavaDoc;
14 import java.util.Map JavaDoc;
15 import java.util.List JavaDoc;
16
17 /**
18  * Various bean property utilities that makes writings of {@link BeanUtil} classes easy.
19  * <p>
20  */

21 public class BeanPropertyUtil {
22
23     // ---------------------------------------------------------------- setter
24

25     /**
26      * Invokes <code>setXxx()</code> method with appropriate conversion if available.
27      * It is assumed that all provided arguments are valid.
28      */

29     public static void invokeSetter(Object JavaDoc bean, Method JavaDoc m, Object JavaDoc value) {
30         Class JavaDoc[] paramTypes = m.getParameterTypes();
31         TypeConverter objconv = TypeConverterManager.lookup(paramTypes[0]);
32         if (objconv != null) {
33             value = objconv.convert(value);
34         }
35         try {
36             m.invoke(bean, new Object JavaDoc[] {value});
37         } catch (IllegalAccessException JavaDoc iaex) {
38             throw new BeanException("Unable to access '" + bean.getClass().getName() + '#' + m.getName() + "()'", iaex);
39         } catch (InvocationTargetException JavaDoc itex) {
40             throw new BeanException("Unable to invoke '" + bean.getClass().getName() + '#' + m.getName() + "()'", itex);
41         }
42     }
43
44     /**
45      * As {@link #invokeSetter(Object, java.lang.reflect.Method, Object)} except it doesn't throw any exception.
46      */

47     public static boolean invokeSetterSilent(Object JavaDoc bean, Method JavaDoc m, Object JavaDoc value) {
48         try {
49             Class JavaDoc[] paramTypes = m.getParameterTypes();
50             TypeConverter objconv = TypeConverterManager.lookup(paramTypes[0]);
51             if (objconv != null) {
52                 value = objconv.convert(value);
53             }
54             m.invoke(bean, new Object JavaDoc[] {value});
55             return true;
56         } catch (Exception JavaDoc ex) {
57             return false;
58         }
59     }
60
61     /**
62      * Invokes <code>getXxx()</code> method of specified bean.
63      * It is assumed that all provided arguments are valid.
64      */

65     public static Object JavaDoc invokeGetter(Object JavaDoc bean, Method JavaDoc m) {
66         try {
67             return m.invoke(bean, new Object JavaDoc[] {});
68         } catch (IllegalAccessException JavaDoc iaex) {
69             throw new BeanException("Unable to access '" + bean.getClass().getName() + '#' + m.getName() + "()'", iaex);
70         } catch (InvocationTargetException JavaDoc itex) {
71             throw new BeanException("Unable to invoke '" + bean.getClass().getName() + '#' + m.getName() + "()'", itex);
72         }
73     }
74
75     /**
76      * Sets field value.
77      */

78     public static void setField(Object JavaDoc bean, Field JavaDoc f, Object JavaDoc value) {
79         TypeConverter objconv = TypeConverterManager.lookup(f.getType());
80         if (objconv != null) {
81             value = objconv.convert(value);
82         }
83         try {
84             f.set(bean, value);
85         } catch (IllegalAccessException JavaDoc iaex) {
86             throw new BeanException("Unable to access '" + bean.getClass().getName() + '#' + f.getName() + '\'', iaex);
87         }
88     }
89
90     /**
91      * Sets field value.
92      */

93     public static boolean setFieldSilent(Object JavaDoc bean, Field JavaDoc f, Object JavaDoc value) {
94         try {
95             TypeConverter objconv = TypeConverterManager.lookup(f.getType());
96             if (objconv != null) {
97                 value = objconv.convert(value);
98             }
99             f.set(bean, value);
100             return true;
101         } catch (Exception JavaDoc ex) {
102             return false;
103         }
104     }
105
106
107     /**
108      * Return value of a field.
109      */

110     public static Object JavaDoc getField(Object JavaDoc bean, Field JavaDoc f) {
111         try {
112             return f.get(bean);
113         } catch (IllegalAccessException JavaDoc iaex) {
114             throw new BeanException("Unable to access '" + bean.getClass().getName() + '#' + f.getName() + '\'', iaex);
115         }
116     }
117
118     // ---------------------------------------------------------------- forced
119

120     /**
121      * Returns the element of an array forced. If value is <code>null</code>, it will be instantiated.
122      * If not the last part of indexed bean property, array will be expanded to the index if necessary.
123      */

124     public static Object JavaDoc arrayForcedGet(BeanProperty beanProperty, Object JavaDoc array, int index) {
125         if (beanProperty.last == false) {
126             int len = Array.getLength(array);
127             if (index >= len) {
128                 Object JavaDoc newArray = Array.newInstance(array.getClass().getComponentType(), index + 1);
129                 System.arraycopy(array, 0, newArray, 0, len);
130                 Method JavaDoc setter = beanProperty.cd.getBeanSetter(beanProperty.name, true);
131                 if (setter != null) {
132                     invokeSetter(beanProperty.bean, setter, newArray);
133                 } else {
134                     Field JavaDoc field = beanProperty.cd.getField(beanProperty.name, true);
135                     if (field == null) {
136                         throw new BeanException("Unable to find setter or field '" + beanProperty + '\'');
137                     }
138                     setField(beanProperty.bean, field, newArray);
139                 }
140                 array = newArray;
141             }
142         }
143         Object JavaDoc value = Array.get(array, index);
144         if (value == null) {
145             Class JavaDoc componentType = array.getClass().getComponentType();
146             try {
147                 value = ReflectUtil.newInstance(componentType);
148             } catch (InstantiationException JavaDoc inex) {
149                 throw new BeanException("Unable to instantiate array element '" + beanProperty + '[' + index + "]'", inex);
150             } catch (IllegalAccessException JavaDoc iaex) {
151                 throw new BeanException("Unable to access array element '" + beanProperty + '[' + index + "]'", iaex);
152             }
153             Array.set(array, index, value);
154         }
155         return value;
156     }
157
158     /**
159      * Sets the array element forced. If index is greater then arrays length, array will be expanded to the index.
160      * If speed is critical, it is better to allocate an array with proper size before using this method.
161      */

162     public static void arrayForcedSet(BeanProperty beanProperty, Object JavaDoc array, int index, Object JavaDoc value) {
163         int len = Array.getLength(array);
164         Class JavaDoc componentType = array.getClass().getComponentType();
165         if (index >= len) {
166             Object JavaDoc newArray = Array.newInstance(componentType, index + 1);
167             System.arraycopy(array, 0, newArray, 0, len);
168             Method JavaDoc setter = beanProperty.cd.getBeanSetter(beanProperty.name, true);
169             if (setter != null) {
170                 invokeSetter(beanProperty.bean, setter, newArray);
171             } else {
172                 Field JavaDoc field = beanProperty.cd.getField(beanProperty.name, true);
173                 if (field == null) {
174                     throw new BeanException("Unable to find setter or field '" + beanProperty + '\'');
175                 }
176                 setField(beanProperty.bean, field, newArray);
177             }
178             array = newArray;
179         }
180         TypeConverter objconv = TypeConverterManager.lookup(componentType);
181         if (objconv != null) {
182             value = objconv.convert(value);
183         }
184         Array.set(array, index, value);
185     }
186
187     /**
188      * Returns the element of an list forced. If value is <code>null</code>, it will be instantiated.
189      * If not the last part of indexed bean property, list will be expanded to the index if necessary.
190      */

191     public static Object JavaDoc listForcedGet(BeanProperty beanProperty, List JavaDoc list, int index) {
192         if (beanProperty.last == false) {
193             int len = list.size();
194             while (index >= len) {
195                 list.add(null);
196                 len++;
197             }
198         }
199         Object JavaDoc value = list.get(index);
200         if (value == null) {
201             value = new HashMap JavaDoc();
202             list.remove(index);
203             list.add(index, value);
204         }
205         return value;
206     }
207
208     /**
209      * Sets the list element forced. If index is greater then list length, list will be expanded to the index.
210      */

211     public static void listForcedSet(List JavaDoc list, int index, Object JavaDoc value) {
212         int len = list.size();
213         while (index >= len) {
214             list.add(null);
215             len++;
216         }
217         list.set(index, value);
218     }
219
220
221     /**
222      * Returns the element of an map forced.
223      * If not the last part of indexed bean property, and value is <code>null</code>,
224      * new HashMap will be returned.
225      */

226     public static Object JavaDoc mapForcedGet(BeanProperty bp, Map JavaDoc map, String JavaDoc key) {
227         Object JavaDoc value = map.get(key);
228         if (bp.last == false) {
229             if (value == null) {
230                 value = new HashMap JavaDoc();
231                 map.put(key, value);
232             }
233         }
234         return value;
235     }
236
237
238     // ---------------------------------------------------------------- index
239

240
241     /**
242      * Extract index string from non-nested property name.
243      * If index is found, it is stripped from bean property name.
244      * If no index is found, it returns null.
245      */

246     public static String JavaDoc extractIndex(BeanProperty beanProperty) {
247         String JavaDoc name = beanProperty.name;
248         int lastNdx = name.length() - 1;
249         if (name.charAt(lastNdx) == ']') {
250             int leftBracketNdx = name.lastIndexOf('[');
251             if (leftBracketNdx != -1) {
252                 beanProperty.name = name.substring(0, leftBracketNdx);
253                 return name.substring(leftBracketNdx + 1, lastNdx);
254             }
255         }
256         return null;
257     }
258
259     // ---------------------------------------------------------------- create property
260

261     /**
262      * Creates new instance for current property name through its setter.
263      * It uses default constructor!
264      */

265     public static Object JavaDoc createBeanProperty(BeanProperty beanProperty) {
266         Method JavaDoc setter = beanProperty.cd.getBeanSetter(beanProperty.name, true);
267         Field JavaDoc field = null;
268         Class JavaDoc type;
269         if (setter != null) {
270             type = setter.getParameterTypes()[0];
271         } else {
272             field = beanProperty.cd.getField(beanProperty.name, true);
273             if (field == null) {
274                 return null;
275             }
276             type = field.getType();
277         }
278         Object JavaDoc newInstance;
279         try {
280             newInstance = ReflectUtil.newInstance(type);
281             if (newInstance == null) {
282                 newInstance = type.newInstance();
283             }
284         } catch (InstantiationException JavaDoc iex) {
285             throw new BeanException("Unable to instantiate '" + beanProperty + "' through its setter.");
286         } catch (IllegalAccessException JavaDoc iaex) {
287             throw new BeanException("Unable to access '" + beanProperty + "' through its setter.");
288         }
289         if (setter != null) {
290             invokeSetter(beanProperty.bean, setter, newInstance);
291         } else {
292             setField(beanProperty.bean, field, newInstance);
293         }
294         return newInstance;
295     }
296
297     /**
298      * Creates new Map property.
299      */

300     public static Map JavaDoc createMapProperty(Map JavaDoc destination, String JavaDoc name) {
301         Map JavaDoc value = new HashMap JavaDoc();
302         destination.put(name, value);
303         return value;
304     }
305
306
307 }
308
Popular Tags