-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathReflectionUtil.java
More file actions
641 lines (516 loc) · 17.1 KB
/
ReflectionUtil.java
File metadata and controls
641 lines (516 loc) · 17.1 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
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
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
package com.winteralexander.gdx.utils;
import com.badlogic.gdx.utils.Array;
import com.badlogic.gdx.utils.ObjectMap;
import java.io.File;
import java.io.IOException;
import java.lang.reflect.*;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.Enumeration;
import java.util.function.Consumer;
import java.util.jar.JarEntry;
import java.util.jar.JarFile;
import java.util.regex.Pattern;
import java.util.stream.Stream;
import static com.winteralexander.gdx.utils.TypeUtil.isPrimitiveBox;
import static com.winteralexander.gdx.utils.Validation.ensureNotNull;
import static com.winteralexander.gdx.utils.collection.CollectionUtil.last;
/**
* Utility class to use reflection on objects
* <p>
* Created on 2018-02-09.
*
* @author Alexander Winter
*/
public class ReflectionUtil {
private ReflectionUtil() {}
@SuppressWarnings("unchecked")
public static <T> T construct(Class<T> type, Object... params) {
ensureNotNull(type, "type");
for(Constructor<?> constructor : type.getDeclaredConstructors()) {
try {
if(!constructor.isAccessible())
constructor.setAccessible(true);
return (T)constructor.newInstance(params);
} catch(InstantiationException | IllegalArgumentException
| IllegalAccessException ignored) {
// continue
} catch(InvocationTargetException ex) {
throw new RuntimeException(ex);
}
}
throw new IllegalArgumentException("No matching constructor found");
}
/**
* Sets the field of an object to a specified value
*
* @param object object to edit field's of
* @param field field to edit
* @param value value to set
*/
public static void set(Object object, String field, Object value) {
ensureNotNull(object, "object");
set(object.getClass(), object, field, value);
}
/**
* Sets the field of an object to a specified value
*
* @param type type of object to set value of
* @param object object to edit field's of, or null if static field
* @param field field to edit
* @param value value to set
*/
public static void set(Class<?> type, Object object, String field, Object value) {
ensureNotNull(type, "type");
ensureNotNull(field, "field");
ensureNotNull(value, "value");
while(type != null) {
try {
Field fieldHandle = type.getDeclaredField(field);
fieldHandle.setAccessible(true);
fieldHandle.set(object, value);
return;
} catch(IllegalAccessException ex) {
throw new RuntimeException(ex);
} catch(NoSuchFieldException ignored) {}
type = type.getSuperclass();
}
throw new IllegalArgumentException("Field not found");
}
@SuppressWarnings("unchecked")
public static <T> T get(Object object, String field) {
return (T)get(object, field, Object.class);
}
/**
* Gets the field of an object for a specified field name
*
* @param object object to edit field's of
* @param field field to edit
* @param type type of field
*/
public static <T> T get(Object object, String field, Class<T> type) {
ensureNotNull(object, "object");
ensureNotNull(field, "field");
ensureNotNull(type, "type");
Class<?> t = object.getClass();
while(t != null) {
try {
Field fieldHandle = t.getDeclaredField(field);
if(!fieldHandle.isAccessible())
fieldHandle.setAccessible(true);
return type.cast(fieldHandle.get(object));
} catch(IllegalAccessException ex) {
throw new RuntimeException(ex);
} catch(NoSuchFieldException ignored) {}
t = t.getSuperclass();
}
throw new IllegalArgumentException("Field " + field + " not found for type "
+ object.getClass());
}
@SuppressWarnings("unchecked")
public static <T> T getStatic(Class<?> type, String field) {
return (T)getStatic(type, field, Object.class);
}
public static <T> T getStatic(Class<?> type, String field, Class<T> returnType) {
ensureNotNull(type, "type");
ensureNotNull(field, "field");
ensureNotNull(returnType, "returnType");
Class<?> origType = type;
while(type != null) {
try {
Field fieldHandle = type.getDeclaredField(field);
if(!fieldHandle.isAccessible())
fieldHandle.setAccessible(true);
return returnType.cast(fieldHandle.get(null));
} catch(IllegalAccessException ex) {
throw new RuntimeException(ex);
} catch(NoSuchFieldException ignored) {}
type = type.getSuperclass();
}
throw new IllegalArgumentException("Field " + field + " not found for type " + origType);
}
public static boolean has(Class<?> type, String field) {
ensureNotNull(type, "type");
ensureNotNull(field, "field");
Class<?> t = type;
while(t != null) {
try {
t.getDeclaredField(field);
return true;
} catch(NoSuchFieldException ignored) {}
t = t.getSuperclass();
}
return false;
}
public static Class<?> getType(Class<?> type, String field) {
ensureNotNull(type, "type");
ensureNotNull(field, "field");
Class<?> t = type;
while(t != null) {
try {
return t.getDeclaredField(field).getType();
} catch(NoSuchFieldException ignored) {}
t = t.getSuperclass();
}
throw new IllegalArgumentException("Field " + field + " not found for type " + type);
}
@SuppressWarnings({"unchecked", "StringEquality"})
public static <T> T call(Object object, String method, Object... params) {
ensureNotNull(object, "object");
ensureNotNull(method, "method");
method = method.intern();
Class<?> t = object.getClass();
while(t != null) {
try {
for(Method methodHandle : t.getDeclaredMethods()) {
if(methodHandle.getName() != method
|| methodHandle.getParameterCount() != params.length)
continue;
if(!methodHandle.isAccessible())
methodHandle.setAccessible(true);
try {
return (T)methodHandle.invoke(object, params);
} catch(IllegalArgumentException ignored) {}
}
} catch(IllegalAccessException | InvocationTargetException ex) {
throw new RuntimeException(ex);
}
t = t.getSuperclass();
}
throw new IllegalArgumentException("Method " + method + " not found for type "
+ object.getClass());
}
@SuppressWarnings({"unchecked", "StringEquality"})
public static <T> T callStatic(Class<?> type, String method, Object... params) {
ensureNotNull(method, "method");
method = method.intern();
Class<?> origType = type;
while(type != null) {
try {
for(Method methodHandle : type.getDeclaredMethods()) {
if(methodHandle.getName() != method
|| methodHandle.getParameterCount() != params.length)
continue;
if(!methodHandle.isAccessible())
methodHandle.setAccessible(true);
try {
return (T)methodHandle.invoke(null, params);
} catch(IllegalArgumentException ignored) {}
}
} catch(IllegalAccessException | InvocationTargetException ex) {
throw new RuntimeException(ex);
}
type = type.getSuperclass();
}
throw new IllegalArgumentException("Method " + method + " not found for type " + origType);
}
public static Array<String> getFields(Class<?> type) {
Array<String> out = new Array<>();
getFields(type, out::add);
return out;
}
public static void getFields(Class<?> type, Consumer<String> out) {
ensureNotNull(type, "type");
ensureNotNull(out, "out");
while(type != null) {
for(Field field : type.getDeclaredFields())
if(!Modifier.isStatic(field.getModifiers()))
out.accept(field.getName());
type = type.getSuperclass();
}
}
public static Array<String> getStaticFields(Class<?> type) {
Array<String> out = new Array<>();
getStaticFields(type, out::add);
return out;
}
public static void getStaticFields(Class<?> type, Consumer<String> out) {
ensureNotNull(type, "type");
ensureNotNull(out, "out");
while(type != null) {
for(Field field : type.getDeclaredFields())
if(Modifier.isStatic(field.getModifiers()))
out.accept(field.getName());
type = type.getSuperclass();
}
}
/**
* Swap all fields value for 2 objects
*
* @param o1 object 1
* @param o2 object 2
*/
public static void swapFields(Object o1, Object o2) {
if(o1 == null || o2 == null)
throw new IllegalArgumentException("Objects must not be null");
if(!o1.getClass().equals(o2.getClass()))
throw new IllegalArgumentException("Objects are not the same type");
Class<?> type = o1.getClass();
while(type != null) {
for(Field field : type.getDeclaredFields()) {
if(Modifier.isStatic(field.getModifiers()))
continue;
if(!field.isAccessible())
field.setAccessible(true);
try {
Object tmp = field.get(o1);
field.set(o1, field.get(o2));
field.set(o2, tmp);
} catch(IllegalAccessException ex) {
throw new RuntimeException(ex);
}
}
type = type.getSuperclass();
}
}
/**
* Clones an object into another
*
* @param source source object
* @param destination destination object
*/
public static void copy(Object source, Object destination) {
ensureNotNull(source, "source");
ensureNotNull(destination, "destination");
if(!source.getClass().equals(destination.getClass()))
throw new IllegalArgumentException("Objects are not the same type");
Class<?> type = source.getClass();
while(type != null) {
for(Field field : type.getDeclaredFields()) {
if(Modifier.isStatic(field.getModifiers()))
continue;
if(!field.isAccessible())
field.setAccessible(true);
try {
field.set(destination, field.get(source));
} catch(IllegalAccessException ex) {
throw new RuntimeException(ex);
}
}
type = type.getSuperclass();
}
}
public static String toPrettyString(Object object) {
return toPrettyString(object, Integer.MAX_VALUE, 0, new Array<>());
}
public static String toPrettyString(Object object, int maxDepth, int indentationLevel) {
return toPrettyString(object, maxDepth, indentationLevel, new Array<>());
}
private static String toPrettyString(Object object,
int maxDepth,
int indentationLevel,
Array<Object> objects) {
objects.add(object);
if(maxDepth <= 0)
return object.toString() + '\n';
StringBuilder sb = new StringBuilder();
String newLine = System.lineSeparator();
Class<?> type = object.getClass();
sb.append(type.getSimpleName())
.append('@')
.append(Integer.toHexString(object.hashCode()))
.append(newLine);
for(int i = 0; i < indentationLevel; i++)
sb.append('\t');
if(type.isArray()) {
if(!Object[].class.isAssignableFrom(type)) {
int length = java.lang.reflect.Array.getLength(object);
Object[] objArr = new Object[length];
for(int i = 0; i < length; i++)
objArr[i] = java.lang.reflect.Array.get(object, i);
object = objArr;
}
sb.append('[').append(newLine);
int n = 0;
for(Object obj : (Object[])object) {
for(int i = 0; i < indentationLevel + 1; i++)
sb.append('\t');
sb.append(n).append(": ");
try {
if(obj == null)
sb.append("null").append(newLine);
else if(obj.getClass().isAssignableFrom(String.class))
sb.append("\"").append(obj).append("\"").append(newLine);
else if(obj.getClass().isPrimitive() || obj.getClass().isEnum()
|| isPrimitiveBox(obj.getClass()))
sb.append(obj).append(newLine);
else if(objects.contains(obj, true))
sb.append(obj.getClass().getSimpleName())
.append('@')
.append(Integer.toHexString(obj.hashCode()))
.append(newLine);
else
sb.append(toPrettyString(obj, maxDepth - 1, indentationLevel + 1, objects));
} catch(Throwable ex) {
sb.append('(')
.append(ex.getClass().getSimpleName())
.append(')')
.append(newLine);
}
n++;
}
for(int i = 0; i < indentationLevel; i++)
sb.append('\t');
sb.append(']').append(newLine);
} else {
sb.append('{').append(newLine);
while(type != null) {
for(Field field : type.getDeclaredFields()) {
if(Modifier.isStatic(field.getModifiers()))
continue;
for(int i = 0; i < indentationLevel + 1; i++)
sb.append('\t');
if(!field.isAccessible())
field.setAccessible(true);
try {
sb.append(field.getName()).append(": ");
Object obj = field.get(object);
if(obj == null)
sb.append("null").append(newLine);
else if(String.class.isAssignableFrom(field.getType()))
sb.append("\"").append(obj).append("\"").append(newLine);
else if(field.getType().isPrimitive() || field.getType().isEnum())
sb.append(obj).append(newLine);
else if(objects.contains(obj, true))
sb.append(obj.getClass().getSimpleName())
.append('@')
.append(Integer.toHexString(obj.hashCode()))
.append(newLine);
else {
sb.append(toPrettyString(obj,
maxDepth - 1,
indentationLevel + 1,
objects));
}
} catch(Throwable ex) {
sb.append("(")
.append(ex.getClass().getSimpleName())
.append(")")
.append(newLine);
}
}
type = type.getSuperclass();
}
for(int i = 0; i < indentationLevel; i++)
sb.append('\t');
sb.append('}').append(newLine);
}
return sb.toString();
}
@SuppressWarnings("raw")
public static boolean disableAccessWarnings() {
try {
Class<?> unsafeClass = Class.forName("sun.misc.Unsafe");
Field field = unsafeClass.getDeclaredField("theUnsafe");
field.setAccessible(true);
Object unsafe = field.get(null);
Method putObjectVolatile = unsafeClass.getDeclaredMethod("putObjectVolatile",
Object.class,
long.class,
Object.class);
Method staticFieldOffset = unsafeClass.getDeclaredMethod("staticFieldOffset",
Field.class);
Class<?> loggerClass = Class.forName("jdk.internal.module.IllegalAccessLogger");
Field loggerField = loggerClass.getDeclaredField("logger");
Long offset = (Long)staticFieldOffset.invoke(unsafe, loggerField);
putObjectVolatile.invoke(unsafe, loggerClass, offset, null);
return true;
} catch(Exception ignored) {
return false;
}
}
public static String getParentStackLocation() {
return getParentStackLocation(3);
}
public static String getParentStackLocation(int parent) {
Thread thread = Thread.currentThread();
StackTraceElement[] elements = thread.getStackTrace();
if(elements.length == 0)
throw new IllegalStateException("Thread not started");
int index = 1 + parent;
if(elements.length <= index)
throw new IllegalStateException("Thread stack not big enough to retrieve the parent "
+ "with depth " + parent);
return last(elements[index].getClassName().split(Pattern.quote("."))) + "#"
+ elements[index].getMethodName() + "() "
+ "(" + elements[index].getFileName() + ":" + elements[index].getLineNumber()
+ ")";
}
/**
* @see #scanClasspath(Array, ObjectMap)
* @return array of files from the class path
*/
public static Array<String> scanClasspath() {
Array<String> out = new Array<>();
scanClasspath(out, null);
return out;
}
/**
* Scans the class path of the current Java process to retrieve all files that are part of it
* (files inside directories and jars in the class path)
* @param files array to fill with files found in the class path
* @param errors per file error map to fill with errors encountered in the process
*/
public static void scanClasspath(Array<String> files, ObjectMap<String, IOException> errors) {
String classpath = System.getProperty("java.class.path");
for(String entry : classpath.split(File.pathSeparator)) {
File entryFile = new File(entry);
try {
if(entryFile.isDirectory())
scanDirectory(entryFile, files);
else if(entryFile.getName().endsWith(".jar"))
scanJar(entryFile, files);
else
throw new IOException("Unrecognized entry: " + entryFile.getName());
} catch(IOException ex) {
if(errors != null)
errors.put(entry, ex);
}
}
}
private static void scanDirectory(File directory, Array<String> out) throws IOException {
try(Stream<Path> stream = Files.walk(directory.toPath())) {
stream.filter(Files::isRegularFile)
.forEach(p -> out.add(directory.toPath().relativize(p).toString()));
}
}
private static void scanJar(File jarFile, Array<String> out) throws IOException {
try(JarFile jar = new JarFile(jarFile)) {
Enumeration<JarEntry> entries = jar.entries();
while(entries.hasMoreElements()) {
JarEntry entry = entries.nextElement();
out.add(entry.getName());
}
}
}
/**
* Filters files from the result of a {@link #scanClasspath(Array, ObjectMap)} and converts
* class paths to class names which can later be converted to classes using
* {@link Class#forName(String)}
*
* @param classpathScanResult iterable of file paths from the class path
* @return array of class names
*/
public static Array<String> getClasses(Iterable<String> classpathScanResult) {
Array<String> classes = new Array<>();
classpathScanResult.forEach(c -> {
if(c.endsWith(".class"))
classes.add(
c.replace(File.separatorChar, '.').replace('/', '.').replace(".class", ""));
});
return classes;
}
/**
* Loads every class from an array of class names
* @param classNames array of class names
* @return array of classes loaded
* @throws ClassNotFoundException if a class failed to be loaded
*/
public static Array<Class<?>> loadClasses(Iterable<String> classNames)
throws ClassNotFoundException {
Array<Class<?>> classes = new Array<>();
for(String className : classNames)
classes.add(Class.forName(className));
return classes;
}
}