View Javadoc

1   /*
2    * Copyright 2002-2009 the original author or authors.
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  
17  package net.sf.json.util;
18  
19  import java.lang.reflect.Field;
20  import java.util.Map;
21  
22  import net.sf.json.JSONException;
23  import net.sf.json.JsonConfig;
24  
25  import org.apache.commons.beanutils.PropertyUtils;
26  
27  /**
28   * Defines a custom setter to be used when setting object values.<br>
29   * Specify with JsonConfig.setJsonPropertySetter().
30   *
31   * @author Gino Miceli <ginomiceli@users.sourceforge.net>
32   * @author Andres Almiray <aalmiray@users.sourceforge.net>
33   */
34  public abstract class PropertySetStrategy {
35     public static final PropertySetStrategy DEFAULT = new DefaultPropertySetStrategy();
36  
37     public abstract void setProperty( Object bean, String key, Object value ) throws JSONException;
38     
39     public void setProperty( Object bean, String key, Object value, JsonConfig jsonConfig ) throws JSONException {
40        setProperty( bean, key, value );
41     }
42  
43     private static final class DefaultPropertySetStrategy extends PropertySetStrategy {
44        public void setProperty( Object bean, String key, Object value ) throws JSONException {
45           setProperty( bean, key, value, new JsonConfig());
46        }
47        
48        public void setProperty( Object bean, String key, Object value, JsonConfig jsonConfig ) throws JSONException {
49           if( bean instanceof Map ){
50              ((Map) bean).put( key, value );
51           } else {
52              if( !jsonConfig.isIgnorePublicFields() ) {
53                 try {
54                    Field field = bean.getClass().getField( key );
55                    if( field != null ) field.set( bean, value );
56                 } catch( Exception e ){
57                    _setProperty( bean, key, value );
58                 }
59              } else {
60                 _setProperty( bean, key, value );
61              }
62           }
63        }
64        
65        private void _setProperty( Object bean, String key, Object value ) {
66           try {
67              PropertyUtils.setSimpleProperty( bean, key, value );
68           } catch( Exception e ) {
69              throw new JSONException( e );
70           }
71        }
72        
73     }
74  }