-
Notifications
You must be signed in to change notification settings - Fork 37.7k
/
Constants.java
369 lines (334 loc) · 12.7 KB
/
Constants.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
/*
* Copyright 2002-2023 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.core;
import java.lang.reflect.Field;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Locale;
import java.util.Map;
import java.util.Set;
import org.springframework.lang.Nullable;
import org.springframework.util.Assert;
import org.springframework.util.ReflectionUtils;
/**
* This class can be used to parse other classes containing constant definitions
* in public static final members. The {@code asXXXX} methods of this class
* allow these constant values to be accessed via their string names.
*
* <p>Consider class Foo containing {@code public static final int CONSTANT1 = 66;}
* An instance of this class wrapping {@code Foo.class} will return the constant value
* of 66 from its {@code asNumber} method given the argument {@code "CONSTANT1"}.
*
* <p>This class is ideal for use in PropertyEditors, enabling them to
* recognize the same names as the constants themselves, and freeing them
* from maintaining their own mapping.
*
* @author Rod Johnson
* @author Juergen Hoeller
* @since 16.03.2003
* @deprecated since 6.1 with no replacement; use an enum, map, or similar custom
* solution instead
*/
@Deprecated(since = "6.1")
public class Constants {
/** The name of the introspected class. */
private final String className;
/** Map from String field name to object value. */
private final Map<String, Object> fieldCache = new HashMap<>();
/**
* Create a new Constants converter class wrapping the given class.
* <p>All <b>public</b> static final variables will be exposed, whatever their type.
* @param clazz the class to analyze
* @throws IllegalArgumentException if the supplied {@code clazz} is {@code null}
*/
public Constants(Class<?> clazz) {
Assert.notNull(clazz, "Class must not be null");
this.className = clazz.getName();
Field[] fields = clazz.getFields();
for (Field field : fields) {
if (ReflectionUtils.isPublicStaticFinal(field)) {
String name = field.getName();
try {
Object value = field.get(null);
this.fieldCache.put(name, value);
}
catch (IllegalAccessException ex) {
// just leave this field and continue
}
}
}
}
/**
* Return the name of the analyzed class.
*/
public final String getClassName() {
return this.className;
}
/**
* Return the number of constants exposed.
*/
public final int getSize() {
return this.fieldCache.size();
}
/**
* Exposes the field cache to subclasses:
* a Map from String field name to object value.
*/
protected final Map<String, Object> getFieldCache() {
return this.fieldCache;
}
/**
* Return a constant value cast to a Number.
* @param code the name of the field (never {@code null})
* @return the Number value
* @throws ConstantException if the field name wasn't found
* or if the type wasn't compatible with Number
* @see #asObject
*/
public Number asNumber(String code) throws ConstantException {
Object obj = asObject(code);
if (!(obj instanceof Number number)) {
throw new ConstantException(this.className, code, "not a Number");
}
return number;
}
/**
* Return a constant value as a String.
* @param code the name of the field (never {@code null})
* @return the String value
* Works even if it's not a string (invokes {@code toString()}).
* @throws ConstantException if the field name wasn't found
* @see #asObject
*/
public String asString(String code) throws ConstantException {
return asObject(code).toString();
}
/**
* Parse the given String (upper or lower case accepted) and return
* the appropriate value if it's the name of a constant field in the
* class that we're analyzing.
* @param code the name of the field (never {@code null})
* @return the Object value
* @throws ConstantException if there's no such field
*/
public Object asObject(String code) throws ConstantException {
Assert.notNull(code, "Code must not be null");
String codeToUse = code.toUpperCase(Locale.ENGLISH);
Object val = this.fieldCache.get(codeToUse);
if (val == null) {
throw new ConstantException(this.className, codeToUse, "not found");
}
return val;
}
/**
* Return all names of the given group of constants.
* <p>Note that this method assumes that constants are named
* in accordance with the standard Java convention for constant
* values (i.e. all uppercase). The supplied {@code namePrefix}
* will be uppercased (in a locale-insensitive fashion) prior to
* the main logic of this method kicking in.
* @param namePrefix prefix of the constant names to search (may be {@code null})
* @return the set of constant names
*/
public Set<String> getNames(@Nullable String namePrefix) {
String prefixToUse = (namePrefix != null ? namePrefix.trim().toUpperCase(Locale.ENGLISH) : "");
Set<String> names = new HashSet<>();
for (String code : this.fieldCache.keySet()) {
if (code.startsWith(prefixToUse)) {
names.add(code);
}
}
return names;
}
/**
* Return all names of the group of constants for the
* given bean property name.
* @param propertyName the name of the bean property
* @return the set of values
* @see #propertyToConstantNamePrefix
*/
public Set<String> getNamesForProperty(String propertyName) {
return getNames(propertyToConstantNamePrefix(propertyName));
}
/**
* Return all names of the given group of constants.
* <p>Note that this method assumes that constants are named
* in accordance with the standard Java convention for constant
* values (i.e. all uppercase). The supplied {@code nameSuffix}
* will be uppercased (in a locale-insensitive fashion) prior to
* the main logic of this method kicking in.
* @param nameSuffix suffix of the constant names to search (may be {@code null})
* @return the set of constant names
*/
public Set<String> getNamesForSuffix(@Nullable String nameSuffix) {
String suffixToUse = (nameSuffix != null ? nameSuffix.trim().toUpperCase(Locale.ENGLISH) : "");
Set<String> names = new HashSet<>();
for (String code : this.fieldCache.keySet()) {
if (code.endsWith(suffixToUse)) {
names.add(code);
}
}
return names;
}
/**
* Return all values of the given group of constants.
* <p>Note that this method assumes that constants are named
* in accordance with the standard Java convention for constant
* values (i.e. all uppercase). The supplied {@code namePrefix}
* will be uppercased (in a locale-insensitive fashion) prior to
* the main logic of this method kicking in.
* @param namePrefix prefix of the constant names to search (may be {@code null})
* @return the set of values
*/
public Set<Object> getValues(@Nullable String namePrefix) {
String prefixToUse = (namePrefix != null ? namePrefix.trim().toUpperCase(Locale.ENGLISH) : "");
Set<Object> values = new HashSet<>();
this.fieldCache.forEach((code, value) -> {
if (code.startsWith(prefixToUse)) {
values.add(value);
}
});
return values;
}
/**
* Return all values of the group of constants for the
* given bean property name.
* @param propertyName the name of the bean property
* @return the set of values
* @see #propertyToConstantNamePrefix
*/
public Set<Object> getValuesForProperty(String propertyName) {
return getValues(propertyToConstantNamePrefix(propertyName));
}
/**
* Return all values of the given group of constants.
* <p>Note that this method assumes that constants are named
* in accordance with the standard Java convention for constant
* values (i.e. all uppercase). The supplied {@code nameSuffix}
* will be uppercased (in a locale-insensitive fashion) prior to
* the main logic of this method kicking in.
* @param nameSuffix suffix of the constant names to search (may be {@code null})
* @return the set of values
*/
public Set<Object> getValuesForSuffix(@Nullable String nameSuffix) {
String suffixToUse = (nameSuffix != null ? nameSuffix.trim().toUpperCase(Locale.ENGLISH) : "");
Set<Object> values = new HashSet<>();
this.fieldCache.forEach((code, value) -> {
if (code.endsWith(suffixToUse)) {
values.add(value);
}
});
return values;
}
/**
* Look up the given value within the given group of constants.
* <p>Will return the first match.
* @param value constant value to look up
* @param namePrefix prefix of the constant names to search (may be {@code null})
* @return the name of the constant field
* @throws ConstantException if the value wasn't found
*/
public String toCode(Object value, @Nullable String namePrefix) throws ConstantException {
String prefixToUse = (namePrefix != null ? namePrefix.trim().toUpperCase(Locale.ENGLISH) : "");
for (Map.Entry<String, Object> entry : this.fieldCache.entrySet()) {
if (entry.getKey().startsWith(prefixToUse) && entry.getValue().equals(value)) {
return entry.getKey();
}
}
throw new ConstantException(this.className, prefixToUse, value);
}
/**
* Look up the given value within the group of constants for
* the given bean property name. Will return the first match.
* @param value constant value to look up
* @param propertyName the name of the bean property
* @return the name of the constant field
* @throws ConstantException if the value wasn't found
* @see #propertyToConstantNamePrefix
*/
public String toCodeForProperty(Object value, String propertyName) throws ConstantException {
return toCode(value, propertyToConstantNamePrefix(propertyName));
}
/**
* Look up the given value within the given group of constants.
* <p>Will return the first match.
* @param value constant value to look up
* @param nameSuffix suffix of the constant names to search (may be {@code null})
* @return the name of the constant field
* @throws ConstantException if the value wasn't found
*/
public String toCodeForSuffix(Object value, @Nullable String nameSuffix) throws ConstantException {
String suffixToUse = (nameSuffix != null ? nameSuffix.trim().toUpperCase(Locale.ENGLISH) : "");
for (Map.Entry<String, Object> entry : this.fieldCache.entrySet()) {
if (entry.getKey().endsWith(suffixToUse) && entry.getValue().equals(value)) {
return entry.getKey();
}
}
throw new ConstantException(this.className, suffixToUse, value);
}
/**
* Convert the given bean property name to a constant name prefix.
* <p>Uses a common naming idiom: turning all lower case characters to
* upper case, and prepending upper case characters with an underscore.
* <p>Example: "imageSize" → "IMAGE_SIZE"<br>
* Example: "imagesize" → "IMAGESIZE".<br>
* Example: "ImageSize" → "_IMAGE_SIZE".<br>
* Example: "IMAGESIZE" → "_I_M_A_G_E_S_I_Z_E"
* @param propertyName the name of the bean property
* @return the corresponding constant name prefix
* @see #getValuesForProperty
* @see #toCodeForProperty
*/
public String propertyToConstantNamePrefix(String propertyName) {
StringBuilder parsedPrefix = new StringBuilder();
for (int i = 0; i < propertyName.length(); i++) {
char c = propertyName.charAt(i);
if (Character.isUpperCase(c)) {
parsedPrefix.append('_');
parsedPrefix.append(c);
}
else {
parsedPrefix.append(Character.toUpperCase(c));
}
}
return parsedPrefix.toString();
}
/**
* Exception thrown when the {@link Constants} class is asked for
* an invalid constant name.
*/
@SuppressWarnings("serial")
public static class ConstantException extends IllegalArgumentException {
/**
* Thrown when an invalid constant name is requested.
* @param className name of the class containing the constant definitions
* @param field invalid constant name
* @param message description of the problem
*/
public ConstantException(String className, String field, String message) {
super("Field '" + field + "' " + message + " in class [" + className + "]");
}
/**
* Thrown when an invalid constant value is looked up.
* @param className name of the class containing the constant definitions
* @param namePrefix prefix of the searched constant names
* @param value the looked up constant value
*/
public ConstantException(String className, String namePrefix, Object value) {
super("No '" + namePrefix + "' field with value '" + value + "' found in class [" + className + "]");
}
}
}