(no commit message)
[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  * Accessing a property of an object.
22  * 
23  * @author Erik Brakkee
24  * 
25  * @param <T>
26  *            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      * 
35      * @param aGetter
36      *            Getter method.
37      * @param aSetter
38      *            Setter method.
39      */
40     public PropertyAccessor(Method aGetter, Method aSetter) {
41         getter = aGetter;
42         setter = aSetter;
43         getter.setAccessible(true);
44         setter.setAccessible(true);
45     }
46
47     @Override
48     public T get(Object aEntity) {
49         try {
50             return (T) getter.invoke(aEntity);
51         } catch (Exception e) {
52             throw new RuntimeException(e);
53         }
54     }
55
56     @Override
57     public void set(Object aEntity, T aValue) {
58         try {
59             setter.invoke(aEntity, aValue);
60         } catch (Exception e) {
61             throw new RuntimeException(e);
62         }
63     }
64
65     /**
66      * @return The getter.
67      */
68     public Method getGetter() {
69         return getter;
70     }
71
72     /**
73      * @return The setter.
74      */
75     public Method getSetter() {
76         return setter;
77     }
78
79     @Override
80     public String toString() {
81         return "propertyInjection(" + getter + ", " + setter + ")";
82     }
83
84     @Override
85     public Class<T> getType() {
86         return (Class<T>) getter.getReturnType();
87     }
88 }