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.lang.reflect.Field;
19  
20  import org.yaml.snakeyaml.error.YAMLException;
21  
22  /**
23   * <p>
24   * A <code>FieldProperty</code> is a <code>Property</code> which is accessed as
25   * a field, without going through accessor methods (setX, getX). The field may
26   * have any scope (public, package, protected, private).
27   * </p>
28   */
29  public class FieldProperty extends GenericProperty {
30      private final Field field;
31  
32      public FieldProperty(Field field) {
33          super(field.getName(), field.getType(), field.getGenericType());
34          this.field = field;
35          field.setAccessible(true);
36      }
37  
38      @Override
39      public void set(Object object, Object value) throws Exception {
40          field.set(object, value);
41      }
42  
43      @Override
44      public Object get(Object object) {
45          try {
46              return field.get(object);
47          } catch (Exception e) {
48              throw new YAMLException("Unable to access field " + field.getName() + " on object "
49                      + object + " : " + e);
50          }
51      }
52  }