View Javadoc

1   /*
2    * Copyright 2004 Carlos Sanchez.
3    *
4    * Licensed under the Apache License, Version 2.0 (the "License");
5    * you may not use this file except in compliance with the License.
6    * You may obtain a copy of the License at
7    *
8    *      http://www.apache.org/licenses/LICENSE-2.0
9    *
10   * Unless required by applicable law or agreed to in writing, software
11   * distributed under the License is distributed on an "AS IS" BASIS,
12   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13   * See the License for the specific language governing permissions and
14   * limitations under the License.
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  }