Type information is now available.
[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 /**
22  * Utility for interfacing to a field of an object. 
23  * 
24  * @author Erik Brakkee
25  *
26  * @param <T> Type of the field. 
27  */
28 public class FieldAccessor<T> implements Accessor<T> {
29     private Field field;
30
31     /**
32      * Constructs the accessor. 
33      * @param aField Field. 
34      */
35     public FieldAccessor(Field aField) {
36         field = aField;
37         field.setAccessible(true);
38     }
39
40     @Override
41     public T get(Object aEntity) {
42         try {
43             T value = (T) field.get(aEntity);
44             return value;
45         } catch (Exception e) {
46             throw new RuntimeException(e);
47         }
48     }
49
50     @Override
51     public void set(Object aEntity, T aValue) {
52         try {
53             field.set(aEntity, aValue);
54         } catch (IllegalAccessException e) {
55             throw new RuntimeException(e.getMessage(), e);
56         }
57     }
58
59     /**
60      * Gets the field. 
61      * @return Field. 
62      */
63     public Field getField() {
64         return field;
65     }
66     
67     @Override
68     public Class<T> getType() {
69         return (Class<T>)field.getType();
70     }
71     
72     @Override
73     public String toString() {
74         return "fieldInjection(" + field + ")"; 
75     }
76 }