1 /*
2 * Copyright 2007-2008 Naoki NOSE.
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 jp.liq.container.reflect;
17
18 import java.lang.annotation.Annotation;
19 import java.lang.reflect.Field;
20
21 import jp.liq.container.reflect.ReflectException.Reason;
22
23 /**
24 * リフレクション API の Field をラップします。
25 * @author nose
26 */
27 public class FieldWrapper extends Member {
28 private final Field field;
29
30 /**
31 * このクラスのインスタンスを構築します。
32 * @param field ラップする Field
33 */
34 public FieldWrapper(Field field) {
35 this.field = field;
36 }
37
38 /**
39 * ラップされた Field を返します。
40 */
41 public Field getField() {
42 return this.field;
43 }
44
45 /**
46 * この Field に値を設定します。
47 * @param target 対象オブジェクト
48 * @param value 設定する値
49 * @throws ReflectException 値の設定に失敗
50 */
51 public void set(Object target, Object value) throws ReflectException {
52 try {
53 field.set(target, value);
54 } catch (Exception e) {
55 throw new ReflectException(e, this, Reason.FAILED_TO_SET_FIELD);
56 }
57 }
58
59 /**
60 * この Field の値を取得します。
61 * @param target 対象オブジェクト
62 * @throws ReflectException 値の取得に失敗
63 */
64 public Object get(Object target) throws ReflectException {
65 try {
66 return field.get(target);
67 } catch (Exception e) {
68 throw new ReflectException(e, this, Reason.FAILED_TO_GET_FIELD);
69 }
70 }
71
72 /**
73 * この Field の名前を取得します。
74 */
75 public String name() {
76 return field.getName();
77 }
78
79 /**
80 * @see jp.liq.container.reflect.Member#isAnnotationPresent(java.lang.Class)
81 */
82 public boolean isAnnotationPresent(Class<? extends Annotation> ann) {
83 return field.getAnnotation(ann) != null;
84 }
85
86 /**
87 * この Field の文字列表現を返します。
88 */
89 public String toString() {
90 return field.toString();
91 }
92
93 /**
94 * @see jp.liq.container.reflect.Member#getModifiers()
95 */
96 @Override
97 protected int getModifiers() {
98 return field.getModifiers();
99 }
100
101 }