1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22 package net.grinder.util;
23
24 import java.beans.IntrospectionException;
25 import java.beans.PropertyDescriptor;
26 import java.lang.reflect.InvocationTargetException;
27 import java.lang.reflect.Method;
28
29 import net.grinder.common.GrinderException;
30
31
32
33
34
35
36
37
38 public final class BooleanProperty {
39 private final Object m_bean;
40 private final Class<?> m_beanClass;
41 private final PropertyDescriptor m_propertyDescriptor;
42
43
44
45
46
47
48
49
50
51 public BooleanProperty(Object bean, String propertyName)
52 throws PropertyException {
53
54 m_bean = bean;
55 m_beanClass = bean.getClass();
56
57 try {
58 m_propertyDescriptor = new PropertyDescriptor(propertyName, m_beanClass);
59 }
60 catch (IntrospectionException e) {
61 throw new PropertyException(
62 "Could not find property '" + propertyName + "' in class '" +
63 m_beanClass + "'", e);
64 }
65
66 final Class<?> propertyType = m_propertyDescriptor.getPropertyType();
67
68 if (!propertyType.equals(Boolean.TYPE) &&
69 !propertyType.equals(Boolean.class)) {
70 throw new PropertyException(toString() + ": property is not boolean");
71 }
72 }
73
74
75
76
77
78
79
80 public boolean get() throws PropertyException {
81
82
83
84
85 final Method readMethod = m_propertyDescriptor.getReadMethod();
86
87 try {
88 final Boolean result = (Boolean)readMethod.invoke(m_bean, new Object[0]);
89 return result.booleanValue();
90 }
91 catch (IllegalAccessException e) {
92 throw new PropertyException(toString() + ": could not read", e);
93 }
94 catch (InvocationTargetException e) {
95 throw new PropertyException(toString() + ": could not read",
96 e.getTargetException());
97 }
98 }
99
100
101
102
103
104
105
106 public void set(boolean value) throws PropertyException {
107
108
109
110 final Method writeMethod = m_propertyDescriptor.getWriteMethod();
111
112 try {
113 writeMethod.invoke(
114 m_bean, new Object[] { value ? Boolean.TRUE : Boolean.FALSE });
115 }
116 catch (IllegalAccessException e) {
117 throw new PropertyException(toString() + ": could not write", e);
118 }
119 catch (InvocationTargetException e) {
120 throw new PropertyException(toString() + ": could not write",
121 e.getTargetException());
122 }
123 }
124
125
126
127
128
129
130 public String toString() {
131 return m_beanClass.getName() + "." + m_propertyDescriptor.getName();
132 }
133
134
135
136
137 public static final class PropertyException extends GrinderException {
138
139 private PropertyException(String message) {
140 super(message);
141 }
142
143 private PropertyException(String message, Throwable t) {
144 super(message, t);
145 }
146 }
147 }