forked from google/gson
-
Notifications
You must be signed in to change notification settings - Fork 1
/
ReflectionHelper.java
277 lines (237 loc) · 10.4 KB
/
ReflectionHelper.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
package com.google.gson.internal.reflect;
import com.google.gson.JsonIOException;
import com.google.gson.internal.GsonBuildConfig;
import java.lang.reflect.AccessibleObject;
import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
public class ReflectionHelper {
private static final RecordHelper RECORD_HELPER;
static {
RecordHelper instance;
try {
// Try to construct the RecordSupportedHelper, if this fails, records are not supported on this JVM.
instance = new RecordSupportedHelper();
} catch (NoSuchMethodException e) {
instance = new RecordNotSupportedHelper();
}
RECORD_HELPER = instance;
}
private ReflectionHelper() {}
/**
* Internal implementation of making an {@link AccessibleObject} accessible.
*
* @param object the object that {@link AccessibleObject#setAccessible(boolean)} should be called on.
* @throws JsonIOException if making the object accessible fails
*/
public static void makeAccessible(AccessibleObject object) throws JsonIOException {
try {
object.setAccessible(true);
} catch (Exception exception) {
String description = getAccessibleObjectDescription(object, false);
throw new JsonIOException("Failed making " + description + " accessible; either increase its visibility"
+ " or write a custom TypeAdapter for its declaring type.", exception);
}
}
/**
* Returns a short string describing the {@link AccessibleObject} in a human-readable way.
* The result is normally shorter than {@link AccessibleObject#toString()} because it omits
* modifiers (e.g. {@code final}) and uses simple names for constructor and method parameter
* types.
*
* @param object object to describe
* @param uppercaseFirstLetter whether the first letter of the description should be uppercased
*/
public static String getAccessibleObjectDescription(AccessibleObject object, boolean uppercaseFirstLetter) {
String description;
if (object instanceof Field) {
description = "field '" + fieldToString((Field) object) + "'";
} else if (object instanceof Method) {
Method method = (Method) object;
StringBuilder methodSignatureBuilder = new StringBuilder(method.getName());
appendExecutableParameters(method, methodSignatureBuilder);
String methodSignature = methodSignatureBuilder.toString();
description = "method '" + method.getDeclaringClass().getName() + "#" + methodSignature + "'";
} else if (object instanceof Constructor) {
description = "constructor '" + constructorToString((Constructor<?>) object) + "'";
} else {
description = "<unknown AccessibleObject> " + object.toString();
}
if (uppercaseFirstLetter && Character.isLowerCase(description.charAt(0))) {
description = Character.toUpperCase(description.charAt(0)) + description.substring(1);
}
return description;
}
/**
* Creates a string representation for a field, omitting modifiers and
* the field type.
*/
public static String fieldToString(Field field) {
return field.getDeclaringClass().getName() + "#" + field.getName();
}
/**
* Creates a string representation for a constructor.
* E.g.: {@code java.lang.String(char[], int, int)}
*/
public static String constructorToString(Constructor<?> constructor) {
StringBuilder stringBuilder = new StringBuilder(constructor.getDeclaringClass().getName());
appendExecutableParameters(constructor, stringBuilder);
return stringBuilder.toString();
}
// Note: Ideally parameter type would be java.lang.reflect.Executable, but that was added in Java 8
private static void appendExecutableParameters(AccessibleObject executable, StringBuilder stringBuilder) {
stringBuilder.append('(');
Class<?>[] parameters = (executable instanceof Method)
? ((Method) executable).getParameterTypes()
: ((Constructor<?>) executable).getParameterTypes();
for (int i = 0; i < parameters.length; i++) {
if (i > 0) {
stringBuilder.append(", ");
}
stringBuilder.append(parameters[i].getSimpleName());
}
stringBuilder.append(')');
}
/**
* Tries making the constructor accessible, returning an exception message
* if this fails.
*
* @param constructor constructor to make accessible
* @return exception message; {@code null} if successful, non-{@code null} if
* unsuccessful
*/
public static String tryMakeAccessible(Constructor<?> constructor) {
try {
constructor.setAccessible(true);
return null;
} catch (Exception exception) {
return "Failed making constructor '" + constructorToString(constructor) + "' accessible;"
+ " either increase its visibility or write a custom InstanceCreator or TypeAdapter for"
// Include the message since it might contain more detailed information
+ " its declaring type: " + exception.getMessage();
}
}
/** If records are supported on the JVM, this is equivalent to a call to Class.isRecord() */
public static boolean isRecord(Class<?> raw) {
return RECORD_HELPER.isRecord(raw);
}
public static String[] getRecordComponentNames(Class<?> raw) {
return RECORD_HELPER.getRecordComponentNames(raw);
}
/** Looks up the record accessor method that corresponds to the given record field */
public static Method getAccessor(Class<?> raw, Field field) {
return RECORD_HELPER.getAccessor(raw, field);
}
public static <T> Constructor<T> getCanonicalRecordConstructor(Class<T> raw) {
return RECORD_HELPER.getCanonicalRecordConstructor(raw);
}
public static RuntimeException createExceptionForUnexpectedIllegalAccess(
IllegalAccessException exception) {
throw new RuntimeException("Unexpected IllegalAccessException occurred (Gson " + GsonBuildConfig.VERSION + ")."
+ " Certain ReflectionAccessFilter features require Java >= 9 to work correctly. If you are not using"
+ " ReflectionAccessFilter, report this to the Gson maintainers.",
exception);
}
private static RuntimeException createExceptionForRecordReflectionException(
ReflectiveOperationException exception) {
throw new RuntimeException("Unexpected ReflectiveOperationException occurred"
+ " (Gson " + GsonBuildConfig.VERSION + ")."
+ " To support Java records, reflection is utilized to read out information"
+ " about records. All these invocations happens after it is established"
+ " that records exist in the JVM. This exception is unexpected behavior.",
exception);
}
/**
* Internal abstraction over reflection when Records are supported.
*/
private abstract static class RecordHelper {
abstract boolean isRecord(Class<?> clazz);
abstract String[] getRecordComponentNames(Class<?> clazz);
abstract <T> Constructor<T> getCanonicalRecordConstructor(Class<T> raw);
public abstract Method getAccessor(Class<?> raw, Field field);
}
private static class RecordSupportedHelper extends RecordHelper {
private final Method isRecord;
private final Method getRecordComponents;
private final Method getName;
private final Method getType;
private RecordSupportedHelper() throws NoSuchMethodException {
isRecord = Class.class.getMethod("isRecord");
getRecordComponents = Class.class.getMethod("getRecordComponents");
// Class java.lang.reflect.RecordComponent
Class<?> classRecordComponent = getRecordComponents.getReturnType().getComponentType();
getName = classRecordComponent.getMethod("getName");
getType = classRecordComponent.getMethod("getType");
}
@Override
boolean isRecord(Class<?> raw) {
try {
return (boolean) isRecord.invoke(raw);
} catch (ReflectiveOperationException e) {
throw createExceptionForRecordReflectionException(e);
}
}
@Override
String[] getRecordComponentNames(Class<?> raw) {
try {
Object[] recordComponents = (Object[]) getRecordComponents.invoke(raw);
String[] componentNames = new String[recordComponents.length];
for (int i = 0; i < recordComponents.length; i++) {
componentNames[i] = (String) getName.invoke(recordComponents[i]);
}
return componentNames;
} catch (ReflectiveOperationException e) {
throw createExceptionForRecordReflectionException(e);
}
}
@Override
public <T> Constructor<T> getCanonicalRecordConstructor(Class<T> raw) {
try {
Object[] recordComponents = (Object[]) getRecordComponents.invoke(raw);
Class<?>[] recordComponentTypes = new Class<?>[recordComponents.length];
for (int i = 0; i < recordComponents.length; i++) {
recordComponentTypes[i] = (Class<?>) getType.invoke(recordComponents[i]);
}
// Uses getDeclaredConstructor because implicit constructor has same visibility as record and might
// therefore not be public
return raw.getDeclaredConstructor(recordComponentTypes);
} catch (ReflectiveOperationException e) {
throw createExceptionForRecordReflectionException(e);
}
}
@Override
public Method getAccessor(Class<?> raw, Field field) {
try {
// Records consists of record components, each with a unique name, a corresponding field and accessor method
// with the same name. Ref.: https://docs.oracle.com/javase/specs/jls/se17/html/jls-8.html#jls-8.10.3
return raw.getMethod(field.getName());
} catch (ReflectiveOperationException e) {
throw createExceptionForRecordReflectionException(e);
}
}
}
/**
* Instance used when records are not supported
*/
private static class RecordNotSupportedHelper extends RecordHelper {
@Override
boolean isRecord(Class<?> clazz) {
return false;
}
@Override
String[] getRecordComponentNames(Class<?> clazz) {
throw new UnsupportedOperationException(
"Records are not supported on this JVM, this method should not be called");
}
@Override
<T> Constructor<T> getCanonicalRecordConstructor(Class<T> raw) {
throw new UnsupportedOperationException(
"Records are not supported on this JVM, this method should not be called");
}
@Override
public Method getAccessor(Class<?> raw, Field field) {
throw new UnsupportedOperationException(
"Records are not supported on this JVM, this method should not be called");
}
}
}