View Javadoc

1   /*
2    *  Copyright 2001-2013 Stephen Colebourne
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 org.joda.beans.impl.map;
17  
18  import java.util.HashMap;
19  import java.util.NoSuchElementException;
20  import java.util.Set;
21  
22  import org.joda.beans.DynamicBean;
23  import org.joda.beans.MetaBean;
24  import org.joda.beans.MetaProperty;
25  import org.joda.beans.Property;
26  import org.joda.beans.impl.BasicProperty;
27  
28  /**
29   * Implementation of a fully dynamic {@code Bean} based on an exposed {@code Map}.
30   * <p>
31   * Properties are dynamic, and can be added and removed at will from the map.
32   * 
33   * @author Stephen Colebourne
34   */
35  public class MapBean extends HashMap<String, Object> implements DynamicBean {
36  
37      /** Serialization version. */
38      private static final long serialVersionUID = 1L;
39  
40      @Override
41      public MetaBean metaBean() {
42          return new MapMetaBean(this);
43      }
44  
45      @Override
46      public Property<Object> property(String name) {
47          return BasicProperty.of(this, metaProperty(name));
48      }
49  
50      MetaProperty<Object> metaProperty(String name) {
51          Object obj = get(name);
52          if (obj == null) {
53              throw new NoSuchElementException("Property not found: " + name);
54          }
55          return MapBeanMetaProperty.of(MapBean.this, name);
56      }
57  
58      @Override
59      public Set<String> propertyNames() {
60          return keySet();
61      }
62  
63      @Override
64      public void propertyDefine(String propertyName, Class<?> propertyType) {
65          // no need to define
66      }
67  
68      @Override
69      public void propertyRemove(String propertyName) {
70          remove(propertyName);
71      }
72  
73      //-----------------------------------------------------------------------
74      /**
75       * Returns a string that summarises the bean.
76       * <p>
77       * The string contains the class name and properties.
78       * 
79       * @return a summary string, not null
80       */
81      @Override
82      public String toString() {
83          return getClass().getSimpleName() + super.toString();
84      }
85  
86  }