Type information is now available.
[utils] / support / general / src / main / java / org / wamblee / reflection / PropertyAccessor.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.Method;
19
20
21 /**
22  * Accessing a property of an object. 
23  * 
24  * @author Erik Brakkee
25  *
26  * @param <T> Type of the property. 
27  */
28 public class PropertyAccessor<T> implements Accessor<T> {
29     private Method getter;
30     private Method setter;
31
32     /**
33      * Constructs the accessor. 
34      * @param aGetter Getter method. 
35      * @param aSetter Setter method. 
36      */
37     public PropertyAccessor(Method aGetter, Method aSetter) {
38         getter = aGetter;
39         setter = aSetter;
40         getter.setAccessible(true);
41         setter.setAccessible(true);
42     }
43
44     @Override
45     public T get(Object aEntity) {
46         try {
47             return (T) getter.invoke(aEntity);
48         } catch (Exception e) {
49             throw new RuntimeException(e);
50         }
51     }
52
53     @Override
54     public void set(Object aEntity, T aValue) {
55         try {
56             setter.invoke(aEntity, aValue);
57         } catch (Exception e) {
58             throw new RuntimeException(e);
59         }
60     }
61
62     /**
63      * @return The getter. 
64      */
65     public Method getGetter() {
66         return getter;
67     }
68
69     /**
70      * @return The setter. 
71      */
72     public Method getSetter() {
73         return setter;
74     }
75     
76     @Override
77     public String toString() {
78         return "propertyInjection(" + getter + ", " + setter + ")"; 
79     }
80     
81     @Override
82     public Class<T> getType() {
83         return (Class<T>)getter.getReturnType();
84     }
85 }