(no commit message)
[utils] / support / general / src / main / java / org / wamblee / reflection / FieldAccessor.java
1 /*
2  * Copyright 2005-2010 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 package org.wamblee.reflection;
17
18 import java.lang.reflect.Field;
19
20 /**
21  * Utility for interfacing to a field of an object.
22  * 
23  * @author Erik Brakkee
24  * 
25  * @param <T>
26  *            Type of the field.
27  */
28 public class FieldAccessor<T> implements Accessor<T> {
29     private Field field;
30
31     /**
32      * Constructs the accessor.
33      * 
34      * @param aField
35      *            Field.
36      */
37     public FieldAccessor(Field aField) {
38         field = aField;
39         field.setAccessible(true);
40     }
41
42     @Override
43     public T get(Object aEntity) {
44         try {
45             T value = (T) field.get(aEntity);
46             return value;
47         } catch (Exception e) {
48             throw new RuntimeException(e);
49         }
50     }
51
52     @Override
53     public void set(Object aEntity, T aValue) {
54         try {
55             field.set(aEntity, aValue);
56         } catch (IllegalAccessException e) {
57             throw new RuntimeException(e.getMessage(), e);
58         }
59     }
60
61     /**
62      * Gets the field.
63      * 
64      * @return Field.
65      */
66     public Field getField() {
67         return field;
68     }
69
70     @Override
71     public Class<T> getType() {
72         return (Class<T>) field.getType();
73     }
74
75     @Override
76     public String toString() {
77         return "fieldInjection(" + field + ")";
78     }
79 }