View Javadoc

1   /**
2    * Copyright (c) 2008-2012, http://www.snakeyaml.org
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.yaml.snakeyaml.introspector;
17  
18  import java.beans.PropertyDescriptor;
19  
20  import org.yaml.snakeyaml.error.YAMLException;
21  
22  /**
23   * <p>
24   * A <code>MethodProperty</code> is a <code>Property</code> which is accessed
25   * through accessor methods (setX, getX). It is possible to have a
26   * <code>MethodProperty</code> which has only setter, only getter, or both. It
27   * is not possible to have a <code>MethodProperty</code> which has neither
28   * setter nor getter.
29   * </p>
30   */
31  public class MethodProperty extends GenericProperty {
32  
33      private final PropertyDescriptor property;
34      private final boolean readable;
35      private final boolean writable;
36  
37      public MethodProperty(PropertyDescriptor property) {
38          super(property.getName(), property.getPropertyType(),
39                  property.getReadMethod() == null ? null : property.getReadMethod()
40                          .getGenericReturnType());
41          this.property = property;
42          this.readable = property.getReadMethod() != null;
43          this.writable = property.getWriteMethod() != null;
44      }
45  
46      @Override
47      public void set(Object object, Object value) throws Exception {
48          property.getWriteMethod().invoke(object, value);
49      }
50  
51      @Override
52      public Object get(Object object) {
53          try {
54              property.getReadMethod().setAccessible(true);// issue 50
55              return property.getReadMethod().invoke(object);
56          } catch (Exception e) {
57              throw new YAMLException("Unable to find getter for property '" + property.getName()
58                      + "' on object " + object + ":" + e);
59          }
60      }
61  
62      @Override
63      public boolean isWritable() {
64          return writable;
65      }
66  
67      @Override
68      public boolean isReadable() {
69          return readable;
70      }
71  }