1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16 package net.sf.oness.common.model.bo;
17
18 import java.lang.reflect.Field;
19 import java.util.Collection;
20
21 import net.sf.oness.common.all.ReflectionToStringBuilder;
22
23 /***
24 * Customized ReflectionToStringBuilder ignoring fields that can't be accessed
25 *
26 * @todo optimize this
27 *
28 * @see org.apache.commons.lang.builder.ReflectionToStringBuilder
29 *
30 * @author Carlos Sanchez
31 * @version $Revision: 1.1 $
32 */
33 public class ExceptionSafeReflectionToStringBuilder extends
34 ReflectionToStringBuilder {
35
36 public ExceptionSafeReflectionToStringBuilder(Object object) {
37 super(object);
38 }
39
40 /***
41 * Check if the field is a collection and try to fetch the size. If there is
42 * an error (as it happens with lazy initialized collections) the field is
43 * not accepted.
44 *
45 * @see org.apache.commons.lang.builder.ReflectionToStringBuilder#accept(java.lang.reflect.Field)
46 */
47 protected boolean accept(Field field) {
48 boolean isCollection = Collection.class.isAssignableFrom(field
49 .getType());
50 if (isCollection) {
51 try {
52 Collection value = (Collection) super.getValue(field);
53 if (value != null)
54 value.size();
55 } catch (Exception e) {
56 this.append(field.getName(), "<can't be accessed>");
57 return false;
58 }
59 }
60 return super.accept(field);
61 }
62 }