-
Notifications
You must be signed in to change notification settings - Fork 145
Expand file tree
/
Copy pathBeans.java
More file actions
318 lines (278 loc) · 11.7 KB
/
Beans.java
File metadata and controls
318 lines (278 loc) · 11.7 KB
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
/*
* Copyright (c) 2008 Nathan Sweet
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation
* files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy,
* modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software
* is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
* OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
* LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR
* IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
package com.esotericsoftware.yamlbeans;
import java.lang.annotation.Annotation;
import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.TreeSet;
import com.esotericsoftware.yamlbeans.YamlConfig.ConstructorParameters;
/** Utility for dealing with beans and public fields.
* @author <a href="mailto:misc@n4te.com">Nathan Sweet</a> */
class Beans {
private Beans () {
}
static public boolean isScalar (Class c) {
return c.isPrimitive() || c == String.class || c == Integer.class || c == Boolean.class || c == Float.class
|| c == Long.class || c == Double.class || c == Short.class || c == Byte.class || c == Character.class;
}
static public DeferredConstruction getDeferredConstruction (Class type, YamlConfig config) {
ConstructorParameters parameters = config.readConfig.constructorParameters.get(type);
if (parameters != null) return new DeferredConstruction(parameters.constructor, parameters.parameterNames);
try {
Class constructorProperties = Class.forName("java.beans.ConstructorProperties");
for (Constructor typeConstructor : type.getConstructors()) {
Annotation annotation = typeConstructor.getAnnotation(constructorProperties);
if (annotation == null) continue;
String[] parameterNames = (String[])constructorProperties.getMethod("value").invoke(annotation, (Object[])null);
return new DeferredConstruction(typeConstructor, parameterNames);
}
} catch (Exception ignored) {
}
return null;
}
static public Object createObject (Class type, boolean privateConstructors) throws InvocationTargetException {
// Use no-arg constructor.
Constructor constructor = null;
for (Constructor typeConstructor : type.getConstructors()) {
if (typeConstructor.getParameterTypes().length == 0) {
constructor = typeConstructor;
break;
}
}
if (constructor == null && privateConstructors) {
// Try a private constructor.
try {
constructor = type.getDeclaredConstructor();
constructor.setAccessible(true);
} catch (SecurityException ignored) {
} catch (NoSuchMethodException ignored) {
}
}
// Otherwise try to use a common implementation.
if (constructor == null) {
try {
if (List.class.isAssignableFrom(type)) {
constructor = ArrayList.class.getConstructor(new Class[0]);
} else if (Set.class.isAssignableFrom(type)) {
constructor = HashSet.class.getConstructor(new Class[0]);
} else if (Map.class.isAssignableFrom(type)) {
constructor = HashMap.class.getConstructor(new Class[0]);
}
} catch (Exception ex) {
throw new InvocationTargetException(ex, "Error getting constructor for class: " + type.getName());
}
}
if (constructor == null)
throw new InvocationTargetException(null, "Unable to find a no-arg constructor for class: " + type.getName());
try {
return constructor.newInstance();
} catch (Exception ex) {
throw new InvocationTargetException(ex, "Error constructing instance of class: " + type.getName());
}
}
static public Set<Property> getProperties (Class type, boolean beanProperties, boolean privateFields, YamlConfig config) {
if (type == null) throw new IllegalArgumentException("type cannot be null.");
Class[] noArgs = new Class[0], oneArg = new Class[1];
Set<Property> properties = new TreeSet();
for (Field field : getAllFields(type)) {
String name = field.getName();
String convertedName = config.propertyNameConverter.convertFieldToPropertyName(field);
if (beanProperties) {
DeferredConstruction deferredConstruction = getDeferredConstruction(type, config);
boolean constructorProperty = deferredConstruction != null && deferredConstruction.hasParameter(name);
String nameUpper = Character.toUpperCase(name.charAt(0)) + name.substring(1);
Method getMethod = null, setMethod = null;
try {
oneArg[0] = field.getType();
setMethod = type.getMethod("set" + nameUpper, oneArg);
} catch (Exception ignored) {
}
try {
getMethod = type.getMethod("get" + nameUpper, noArgs);
} catch (Exception ignored) {
}
if (getMethod != null && (setMethod != null || constructorProperty)) {
properties.add(new MethodProperty(name, setMethod, getMethod, convertedName));
continue;
}
}
int modifiers = field.getModifiers();
if (Modifier.isStatic(modifiers) || Modifier.isTransient(modifiers)) continue;
if (!Modifier.isPublic(modifiers)) {
if (!privateFields) continue;
field.setAccessible(true);
}
properties.add(new FieldProperty(field, convertedName));
}
return properties;
}
static public Property getProperty (Class type, String name, boolean beanProperties, boolean privateFields, YamlConfig config) {
if (type == null) throw new IllegalArgumentException("type cannot be null.");
if (name == null || name.length() == 0) throw new IllegalArgumentException("name cannot be null or empty.");
Class[] noArgs = new Class[0], oneArg = new Class[1];
for (Field field : getAllFields(type)) {
String convertedName = config.propertyNameConverter.convertFieldToPropertyName(field);
if (!name.equals(convertedName)) continue;
if (beanProperties) {
DeferredConstruction deferredConstruction = getDeferredConstruction(type, config);
boolean constructorProperty = deferredConstruction != null && deferredConstruction.hasParameter(field.getName());
String nameUpper = Character.toUpperCase(field.getName().charAt(0)) + field.getName().substring(1);
Method getMethod = null, setMethod = null;
try {
oneArg[0] = field.getType();
setMethod = type.getMethod("set" + nameUpper, oneArg);
} catch (Exception ignored) {
}
try {
getMethod = type.getMethod("get" + nameUpper, noArgs);
} catch (Exception ignored) {
}
if (getMethod != null && (setMethod != null || constructorProperty))
return new MethodProperty(field.getName(), setMethod, getMethod, convertedName);
}
int modifiers = field.getModifiers();
if (Modifier.isStatic(modifiers) || Modifier.isTransient(modifiers)) continue;
if (!Modifier.isPublic(modifiers)) {
if (!privateFields) continue;
field.setAccessible(true);
}
return new FieldProperty(field, convertedName);
}
return null;
}
static private ArrayList<Field> getAllFields (Class type) {
ArrayList<Field> allFields = new ArrayList();
Class nextClass = type;
while (nextClass != null && nextClass != Object.class) {
Collections.addAll(allFields, nextClass.getDeclaredFields());
nextClass = nextClass.getSuperclass();
}
return allFields;
}
static public class MethodProperty extends Property {
private final Method setMethod, getMethod;
public MethodProperty (String name, Method setMethod, Method getMethod, String convertedName) {
super(getMethod.getDeclaringClass(), name, getMethod.getReturnType(), convertedName);
this.setMethod = setMethod;
this.getMethod = getMethod;
}
public void set (Object object, Object value) throws Exception {
if (object instanceof DeferredConstruction) {
((DeferredConstruction)object).storeProperty(this, value);
return;
}
setMethod.invoke(object, value);
}
public Object get (Object object) throws Exception {
return getMethod.invoke(object);
}
}
static public class FieldProperty extends Property {
private final Field field;
public FieldProperty (Field field, String convertedName) {
super(field.getDeclaringClass(), field.getName(), field.getType(), convertedName);
this.field = field;
}
public void set (Object object, Object value) throws Exception {
if (object instanceof DeferredConstruction) {
((DeferredConstruction)object).storeProperty(this, value);
return;
}
field.set(object, value);
}
public Object get (Object object) throws Exception {
return field.get(object);
}
}
static public abstract class Property implements Comparable<Property> {
private final Class declaringClass;
private final String name;
private final Class type;
private final String convertedName;
Property (Class declaringClass, String name, Class type, String convertedName) {
this.declaringClass = declaringClass;
this.name = name;
this.type = type;
this.convertedName = convertedName;
}
public int hashCode () {
final int prime = 31;
int result = 1;
result = prime * result + ((declaringClass == null) ? 0 : declaringClass.hashCode());
result = prime * result + ((name == null) ? 0 : name.hashCode());
result = prime * result + ((type == null) ? 0 : type.hashCode());
result = prime * result + ((convertedName == null) ? 0 : convertedName.hashCode());
return result;
}
public boolean equals (Object obj) {
if (this == obj) return true;
if (obj == null) return false;
if (getClass() != obj.getClass()) return false;
Property other = (Property)obj;
if (declaringClass == null) {
if (other.declaringClass != null) return false;
} else if (!declaringClass.equals(other.declaringClass)) return false;
if (name == null) {
if (other.name != null) return false;
} else if (!name.equals(other.name)) return false;
if (type == null) {
if (other.type != null) return false;
} else if (!type.equals(other.type)) return false;
if (convertedName == null) {
if (other.convertedName != null) return false;
} else if (!convertedName.equals(other.convertedName)) return false;
return true;
}
public Class getDeclaringClass () {
return declaringClass;
}
public Class getType () {
return type;
}
public String getName () {
return name;
}
public String getConvertedName() {
return convertedName;
}
public String toString () {
return name;
}
public int compareTo (Property o) {
int comparison = name.compareTo(o.name);
if (comparison != 0) {
// Sort id and name above all other fields.
if (name.equals("id")) return -1;
if (o.name.equals("id")) return 1;
if (name.equals("name")) return -1;
if (o.name.equals("name")) return 1;
}
return comparison;
}
abstract public void set (Object object, Object value) throws Exception;
abstract public Object get (Object object) throws Exception;
}
}