-
-
Notifications
You must be signed in to change notification settings - Fork 1.4k
/
ReflectionUtils.java
1331 lines (1170 loc) · 46.7 KB
/
ReflectionUtils.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
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
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
* Copyright 2015-2018 the original author or authors.
*
* All rights reserved. This program and the accompanying materials are
* made available under the terms of the Eclipse Public License v2.0 which
* accompanies this distribution and is available at
*
* http://www.eclipse.org/legal/epl-v20.html
*/
package org.junit.platform.commons.util;
import static java.util.stream.Collectors.toCollection;
import static java.util.stream.Collectors.toList;
import static java.util.stream.Collectors.toSet;
import static org.apiguardian.api.API.Status.INTERNAL;
import static org.junit.platform.commons.util.CollectionUtils.toUnmodifiableList;
import static org.junit.platform.commons.util.ReflectionUtils.HierarchyTraversalMode.BOTTOM_UP;
import static org.junit.platform.commons.util.ReflectionUtils.HierarchyTraversalMode.TOP_DOWN;
import java.io.File;
import java.lang.reflect.AccessibleObject;
import java.lang.reflect.Array;
import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.GenericArrayType;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Member;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.lang.reflect.Type;
import java.lang.reflect.TypeVariable;
import java.net.URI;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.Set;
import java.util.function.Predicate;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.apiguardian.api.API;
import org.junit.platform.commons.JUnitException;
/**
* Collection of utilities for working with the Java reflection APIs.
*
* <h3>DISCLAIMER</h3>
*
* <p>These utilities are intended solely for usage within the JUnit framework
* itself. <strong>Any usage by external parties is not supported.</strong>
* Use at your own risk!
*
* <p>Some utilities are published via the maintained {@code ReflectionSupport}
* class.
*
* @since 1.0
* @see org.junit.platform.commons.support.ReflectionSupport
*/
@API(status = INTERNAL, since = "1.0")
public final class ReflectionUtils {
///CLOVER:OFF
private ReflectionUtils() {
/* no-op */
}
///CLOVER:ON
/**
* Modes in which a hierarchy can be traversed — for example, when
* searching for methods or fields within a class hierarchy.
*/
public enum HierarchyTraversalMode {
/**
* Traverse the hierarchy using top-down semantics.
*/
TOP_DOWN,
/**
* Traverse the hierarchy using bottom-up semantics.
*/
BOTTOM_UP;
}
// Pattern: [fully qualified class name]#[methodName]((comma-separated list of parameter type names))
private static final Pattern FULLY_QUALIFIED_METHOD_NAME_PATTERN = Pattern.compile("(.+)#([^()]+?)(\\((.*)\\))?");
// Pattern: "[Ljava.lang.String;", "[[[[Ljava.lang.String;", etc.
private static final Pattern VM_INTERNAL_OBJECT_ARRAY_PATTERN = Pattern.compile("^(\\[+)L(.+);$");
/**
* Pattern: "[x", "[[[[x", etc., where x is Z, B, C, D, F, I, J, S, etc.
*
* <p>The pattern intentionally captures the last bracket with the
* capital letter so that the combination can be looked up via
* {@link #classNameToTypeMap}. For example, the last matched group
* will contain {@code "[I"} instead of simply {@code "I"}.
*
* @see Class#getName()
*/
private static final Pattern VM_INTERNAL_PRIMITIVE_ARRAY_PATTERN = Pattern.compile("^(\\[+)(\\[[ZBCDFIJS])$");
// Pattern: "java.lang.String[]", "int[]", "int[][][][]", etc.
private static final Pattern SOURCE_CODE_SYNTAX_ARRAY_PATTERN = Pattern.compile("^([^\\[\\]]+)((\\[\\])+)+$");
private static final Class<?>[] EMPTY_CLASS_ARRAY = new Class<?>[0];
private static final ClasspathScanner classpathScanner = new ClasspathScanner(
ClassLoaderUtils::getDefaultClassLoader, ReflectionUtils::loadClass);
/**
* Internal cache of common class names mapped to their types.
*/
private static final Map<String, Class<?>> classNameToTypeMap;
/**
* Internal cache of primitive types mapped to their wrapper types.
*/
private static final Map<Class<?>, Class<?>> primitiveToWrapperMap;
static {
// @formatter:off
List<Class<?>> commonTypes = Arrays.asList(
boolean.class,
byte.class,
char.class,
short.class,
int.class,
long.class,
float.class,
double.class,
boolean[].class,
byte[].class,
char[].class,
short[].class,
int[].class,
long[].class,
float[].class,
double[].class,
boolean[][].class,
byte[][].class,
char[][].class,
short[][].class,
int[][].class,
long[][].class,
float[][].class,
double[][].class,
Boolean.class,
Byte.class,
Character.class,
Short.class,
Integer.class,
Long.class,
Float.class,
Double.class,
String.class,
Boolean[].class,
Byte[].class,
Character[].class,
Short[].class,
Integer[].class,
Long[].class,
Float[].class,
Double[].class,
String[].class,
Boolean[][].class,
Byte[][].class,
Character[][].class,
Short[][].class,
Integer[][].class,
Long[][].class,
Float[][].class,
Double[][].class,
String[][].class
);
// @formatter:on
Map<String, Class<?>> classNamesToTypes = new HashMap<>(64);
commonTypes.forEach(type -> {
classNamesToTypes.put(type.getName(), type);
classNamesToTypes.put(type.getCanonicalName(), type);
});
classNameToTypeMap = Collections.unmodifiableMap(classNamesToTypes);
Map<Class<?>, Class<?>> primitivesToWrappers = new HashMap<>(8);
primitivesToWrappers.put(boolean.class, Boolean.class);
primitivesToWrappers.put(byte.class, Byte.class);
primitivesToWrappers.put(char.class, Character.class);
primitivesToWrappers.put(short.class, Short.class);
primitivesToWrappers.put(int.class, Integer.class);
primitivesToWrappers.put(long.class, Long.class);
primitivesToWrappers.put(float.class, Float.class);
primitivesToWrappers.put(double.class, Double.class);
primitiveToWrapperMap = Collections.unmodifiableMap(primitivesToWrappers);
}
public static boolean isPublic(Class<?> clazz) {
return Modifier.isPublic(clazz.getModifiers());
}
public static boolean isPublic(Member member) {
return Modifier.isPublic(member.getModifiers());
}
public static boolean isPrivate(Class<?> clazz) {
return Modifier.isPrivate(clazz.getModifiers());
}
public static boolean isPrivate(Member member) {
return Modifier.isPrivate(member.getModifiers());
}
public static boolean isNotPrivate(Member member) {
return !isPrivate(member);
}
public static boolean isAbstract(Class<?> clazz) {
return Modifier.isAbstract(clazz.getModifiers());
}
public static boolean isAbstract(Member member) {
return Modifier.isAbstract(member.getModifiers());
}
public static boolean isStatic(Class<?> clazz) {
return Modifier.isStatic(clazz.getModifiers());
}
public static boolean isStatic(Member member) {
return Modifier.isStatic(member.getModifiers());
}
public static boolean isNotStatic(Member member) {
return !isStatic(member);
}
public static boolean isInnerClass(Class<?> clazz) {
return clazz.isMemberClass() && !isStatic(clazz);
}
public static boolean returnsVoid(Method method) {
return method.getReturnType().equals(Void.TYPE);
}
/**
* Determine if the supplied object is an array.
*
* @param obj the object to test; potentially {@code null}
* @return {@code true} if the object is an array
*/
public static boolean isArray(Object obj) {
return (obj != null && obj.getClass().isArray());
}
/**
* Determine if the supplied object can be assigned to the supplied type
* for the purpose of reflective method invocations.
*
* <p>In contrast to {@link Class#isInstance(Object)}, this method returns
* {@code true} if the supplied type represents a primitive type whose
* wrapper matches the supplied object's type.
*
* <p>Returns {@code true} if the supplied object is {@code null} and the
* supplied type does not represent a primitive type.
*
* @param obj the object to test for assignment compatibility; potentially {@code null}
* @param type the type to check against; never {@code null}
* @return {@code true} if the object is assignment compatible
* @see Class#isInstance(Object)
* @see Class#isAssignableFrom(Class)
*/
public static boolean isAssignableTo(Object obj, Class<?> type) {
Preconditions.notNull(type, "type must not be null");
if (obj == null) {
return !type.isPrimitive();
}
if (type.isInstance(obj)) {
return true;
}
if (type.isPrimitive()) {
return primitiveToWrapperMap.get(type) == obj.getClass();
}
return false;
}
/**
* Get the wrapper type for the supplied primitive type.
*
* @param type the primitive type for which to retrieve the wrapper type
* @return the corresponding wrapper type or {@code null} if the
* supplied type is {@code null} or not a primitive type
*/
public static Class<?> getWrapperType(Class<?> type) {
return primitiveToWrapperMap.get(type);
}
/**
* @see org.junit.platform.commons.support.ReflectionSupport#newInstance(Class, Object...)
* @see #newInstance(Constructor, Object...)
*/
public static <T> T newInstance(Class<T> clazz, Object... args) {
Preconditions.notNull(clazz, "Class must not be null");
Preconditions.notNull(args, "Argument array must not be null");
Preconditions.containsNoNullElements(args, "Individual arguments must not be null");
try {
Class<?>[] parameterTypes = Arrays.stream(args).map(Object::getClass).toArray(Class[]::new);
return newInstance(clazz.getDeclaredConstructor(parameterTypes), args);
}
catch (Throwable t) {
throw ExceptionUtils.throwAsUncheckedException(getUnderlyingCause(t));
}
}
/**
* Create a new instance of type {@code T} by invoking the supplied constructor
* with the supplied arguments.
*
* <p>The constructor will be made accessible if necessary, and any checked
* exception will be {@linkplain ExceptionUtils#throwAsUncheckedException masked}
* as an unchecked exception.
*
* @param constructor the constructor to invoke; never {@code null}
* @param args the arguments to pass to the constructor
* @return the new instance; never {@code null}
* @see #newInstance(Class, Object...)
* @see ExceptionUtils#throwAsUncheckedException(Throwable)
*/
public static <T> T newInstance(Constructor<T> constructor, Object... args) {
Preconditions.notNull(constructor, "Constructor must not be null");
try {
return makeAccessible(constructor).newInstance(args);
}
catch (Throwable t) {
throw ExceptionUtils.throwAsUncheckedException(getUnderlyingCause(t));
}
}
/**
* Read the value of a potentially inaccessible or nonexistent field.
*
* <p>If the field does not exist, an exception occurs while reading it, or
* the value of the field is {@code null}, an empty {@link Optional} is
* returned.
*
* @param clazz the class where the field is declared; never {@code null}
* @param fieldName the name of the field; never {@code null} or empty
* @param instance the instance from where the value is to be read; may
* be {@code null} for a static field
* @see #readFieldValue(Field)
* @see #readFieldValue(Field, Object)
*/
public static <T> Optional<Object> readFieldValue(Class<T> clazz, String fieldName, T instance) {
Preconditions.notNull(clazz, "Class must not be null");
Preconditions.notBlank(fieldName, "Field name must not be null or blank");
Field field = null;
try {
field = makeAccessible(clazz.getDeclaredField(fieldName));
}
catch (Throwable t) {
BlacklistedExceptions.rethrowIfBlacklisted(t);
return Optional.empty();
}
return readFieldValue(field, instance);
}
/**
* Read the value of a potentially inaccessible static field.
*
* <p>If an exception occurs while reading the field or if the value of the
* field is {@code null}, an empty {@link Optional} is returned.
*
* @param field the field to read; never {@code null}
* @see #readFieldValue(Field, Object)
* @see #readFieldValue(Class, String, Object)
*/
public static Optional<Object> readFieldValue(Field field) {
return readFieldValue(field, null);
}
/**
* Read the value of a potentially inaccessible field.
*
* <p>If an exception occurs while reading the field or if the value of the
* field is {@code null}, an empty {@link Optional} is returned.
*
* @param field the field to read; never {@code null}
* @param instance the instance from which the value is to be read; may
* be {@code null} for a static field
* @see #readFieldValue(Field)
* @see #readFieldValue(Class, String, Object)
*/
public static <T> Optional<Object> readFieldValue(Field field, T instance) {
Preconditions.notNull(field, "Field must not be null");
try {
makeAccessible(field);
return Optional.ofNullable(field.get(instance));
}
catch (Throwable t) {
BlacklistedExceptions.rethrowIfBlacklisted(t);
return Optional.empty();
}
}
/**
* @see org.junit.platform.commons.support.ReflectionSupport#invokeMethod(Method, Object, Object...)
*/
public static Object invokeMethod(Method method, Object target, Object... args) {
Preconditions.notNull(method, "Method must not be null");
Preconditions.condition((target != null || isStatic(method)),
() -> String.format("Cannot invoke non-static method [%s] on a null target.", method.toGenericString()));
try {
return makeAccessible(method).invoke(target, args);
}
catch (Throwable t) {
throw ExceptionUtils.throwAsUncheckedException(getUnderlyingCause(t));
}
}
/**
* @see org.junit.platform.commons.support.ReflectionSupport#loadClass(String)
*/
public static Optional<Class<?>> loadClass(String name) {
return loadClass(name, ClassLoaderUtils.getDefaultClassLoader());
}
/**
* Load a class by its <em>primitive name</em> or <em>fully qualified name</em>,
* using the supplied {@link ClassLoader}.
*
* <p>See {@link org.junit.platform.commons.support.ReflectionSupport#loadClass(String)}
* for details on support for class names for arrays.
*
* @param name the name of the class to load; never {@code null} or blank
* @param classLoader the {@code ClassLoader} to use; never {@code null}
* @see #loadClass(String)
*/
public static Optional<Class<?>> loadClass(String name, ClassLoader classLoader) {
Preconditions.notBlank(name, "Class name must not be null or blank");
Preconditions.notNull(classLoader, "ClassLoader must not be null");
name = name.trim();
if (classNameToTypeMap.containsKey(name)) {
return Optional.of(classNameToTypeMap.get(name));
}
try {
Matcher matcher;
// Primitive arrays such as "[I", "[[[[D", etc.
matcher = VM_INTERNAL_PRIMITIVE_ARRAY_PATTERN.matcher(name);
if (matcher.matches()) {
String brackets = matcher.group(1);
String componentTypeName = matcher.group(2);
// Calculate dimensions by counting brackets.
int dimensions = brackets.length();
return loadArrayType(classLoader, componentTypeName, dimensions);
}
// Object arrays such as "[Ljava.lang.String;", "[[[[Ljava.lang.String;", etc.
matcher = VM_INTERNAL_OBJECT_ARRAY_PATTERN.matcher(name);
if (matcher.matches()) {
String brackets = matcher.group(1);
String componentTypeName = matcher.group(2);
// Calculate dimensions by counting brackets.
int dimensions = brackets.length();
return loadArrayType(classLoader, componentTypeName, dimensions);
}
// Arrays such as "java.lang.String[]", "int[]", "int[][][][]", etc.
matcher = SOURCE_CODE_SYNTAX_ARRAY_PATTERN.matcher(name);
if (matcher.matches()) {
String componentTypeName = matcher.group(1);
String bracketPairs = matcher.group(2);
// Calculate dimensions by counting bracket pairs.
int dimensions = bracketPairs.length() / 2;
return loadArrayType(classLoader, componentTypeName, dimensions);
}
// Fallback to standard VM class loading
return Optional.of(classLoader.loadClass(name));
}
catch (ClassNotFoundException ex) {
return Optional.empty();
}
}
private static Optional<Class<?>> loadArrayType(ClassLoader classLoader, String componentTypeName, int dimensions)
throws ClassNotFoundException {
Class<?> componentType = classNameToTypeMap.containsKey(componentTypeName)
? classNameToTypeMap.get(componentTypeName)
: classLoader.loadClass(componentTypeName);
return Optional.of(Array.newInstance(componentType, new int[dimensions]).getClass());
}
/**
* Load a method by its <em>fully qualified name</em>.
*
* <p>The following formats are supported.
*
* <ul>
* <li>{@code [fully qualified class name]#[methodName]}</li>
* <li>{@code [fully qualified class name]#[methodName](parameter type list)}
* </ul>
*
* <p>The <em>parameter type list</em> is a comma-separated list of primitive
* names or fully qualified class names for the types of parameters accepted
* by the method.
*
* <p>See {@link #loadClass(String, ClassLoader)} for details on the supported
* syntax for array parameter types.
*
* <h3>Examples</h3>
*
* <table border="1">
* <tr><th>Method</th><th>Fully Qualified Method Name</th></tr>
* <tr><td>{@code java.lang.String.chars()}</td><td>{@code java.lang.String#chars}</td></tr>
* <tr><td>{@code java.lang.String.chars()}</td><td>{@code java.lang.String#chars()}</td></tr>
* <tr><td>{@code java.lang.String.equalsIgnoreCase(String)}</td><td>{@code java.lang.String#equalsIgnoreCase(java.lang.String)}</td></tr>
* <tr><td>{@code java.lang.String.substring(int, int)}</td><td>{@code java.lang.String#substring(int, int)}</td></tr>
* <tr><td>{@code example.Calc.avg(int[])}</td><td>{@code example.Calc#avg([I)}</td></tr>
* <tr><td>{@code example.Calc.avg(int[])}</td><td>{@code example.Calc#avg(int[])}</td></tr>
* <tr><td>{@code example.Matrix.multiply(double[][])}</td><td>{@code example.Matrix#multiply([[D)}</td></tr>
* <tr><td>{@code example.Matrix.multiply(double[][])}</td><td>{@code example.Matrix#multiply(double[][])}</td></tr>
* <tr><td>{@code example.Service.process(String[])}</td><td>{@code example.Service#process([Ljava.lang.String;)}</td></tr>
* <tr><td>{@code example.Service.process(String[])}</td><td>{@code example.Service#process(java.lang.String[])}</td></tr>
* <tr><td>{@code example.Service.process(String[][])}</td><td>{@code example.Service#process([[Ljava.lang.String;)}</td></tr>
* <tr><td>{@code example.Service.process(String[][])}</td><td>{@code example.Service#process(java.lang.String[][])}</td></tr>
* </table>
*
* @param fullyQualifiedMethodName the fully qualified name of the method to load;
* never {@code null} or blank
* @return an {@code Optional} containing the method; never {@code null} but
* potentially empty
* @see #getFullyQualifiedMethodName(Class, String, Class...)
*/
public static Optional<Method> loadMethod(String fullyQualifiedMethodName) {
Preconditions.notBlank(fullyQualifiedMethodName, "Fully qualified method name must not be null or blank");
String fqmn = fullyQualifiedMethodName.trim();
Matcher matcher = FULLY_QUALIFIED_METHOD_NAME_PATTERN.matcher(fqmn);
Preconditions.condition(matcher.matches(),
() -> String.format("Fully qualified method name [%s] does not match pattern [%s]", fqmn,
FULLY_QUALIFIED_METHOD_NAME_PATTERN));
String className = matcher.group(1);
String methodName = matcher.group(2);
// Note: group #3 includes the parameter types enclosed in parentheses;
// group #4 contains the actual parameter types.
String parameterTypeNames = matcher.group(4);
Optional<Class<?>> classOptional = loadClass(className);
if (classOptional.isPresent()) {
try {
return findMethod(classOptional.get(), methodName.trim(), parameterTypeNames);
}
catch (Exception ex) {
/* ignore */
}
}
return Optional.empty();
}
/**
* Build the <em>fully qualified method name</em> for the method described by the
* supplied class, method name, and parameter types.
*
* <p>See {@link #loadMethod(String)} for details on the format.
*
* @param clazz the class that declares the method; never {@code null}
* @param methodName the name of the method; never {@code null} or blank
* @param parameterTypes the parameter types of the method; may be {@code null} or empty
* @return fully qualified method name; never {@code null}
* @see #loadMethod(String)
*/
public static String getFullyQualifiedMethodName(Class<?> clazz, String methodName, Class<?>... parameterTypes) {
Preconditions.notNull(clazz, "Class must not be null");
Preconditions.notBlank(methodName, "Method name must not be null or blank");
return String.format("%s#%s(%s)", clazz.getName(), methodName, ClassUtils.nullSafeToString(parameterTypes));
}
/**
* Get the outermost instance of the required type, searching recursively
* through enclosing instances.
*
* <p>If the supplied inner object is of the required type, it will simply
* be returned.
*
* @param inner the inner object from which to begin the search; never {@code null}
* @param requiredType the required type of the outermost instance; never {@code null}
* @return an {@code Optional} containing the outermost instance; never {@code null}
* but potentially empty
*/
public static Optional<Object> getOutermostInstance(Object inner, Class<?> requiredType) {
Preconditions.notNull(inner, "inner object must not be null");
Preconditions.notNull(requiredType, "requiredType must not be null");
if (requiredType.isInstance(inner)) {
return Optional.of(inner);
}
Optional<Object> candidate = getOuterInstance(inner);
if (candidate.isPresent()) {
return getOutermostInstance(candidate.get(), requiredType);
}
return Optional.empty();
}
private static Optional<Object> getOuterInstance(Object inner) {
// This is risky since it depends on the name of the field which is nowhere guaranteed
// but has been stable so far in all JDKs
// @formatter:off
return Arrays.stream(inner.getClass().getDeclaredFields())
.filter(field -> field.getName().startsWith("this$"))
.findFirst()
.map(field -> {
try {
return makeAccessible(field).get(inner);
}
catch (Throwable t) {
throw ExceptionUtils.throwAsUncheckedException(t);
}
});
// @formatter:on
}
public static Set<Path> getAllClasspathRootDirectories() {
// This is quite a hack, since sometimes the classpath is quite different
String fullClassPath = System.getProperty("java.class.path");
// @formatter:off
return Arrays.stream(fullClassPath.split(File.pathSeparator))
.map(Paths::get)
.filter(Files::isDirectory)
.collect(toSet());
// @formatter:on
}
/**
* @see org.junit.platform.commons.support.ReflectionSupport#findAllClassesInClasspathRoot(URI, Predicate, Predicate)
*/
public static List<Class<?>> findAllClassesInClasspathRoot(URI root, Predicate<Class<?>> classFilter,
Predicate<String> classNameFilter) {
// unmodifiable since returned by public, non-internal method(s)
return findAllClassesInClasspathRoot(root, ClassFilter.of(classNameFilter, classFilter));
}
@API(status = INTERNAL, since = "1.1")
public static List<Class<?>> findAllClassesInClasspathRoot(URI root, ClassFilter classFilter) {
return Collections.unmodifiableList(classpathScanner.scanForClassesInClasspathRoot(root, classFilter));
}
/**
* @see org.junit.platform.commons.support.ReflectionSupport#findAllClassesInPackage(String, Predicate, Predicate)
*/
public static List<Class<?>> findAllClassesInPackage(String basePackageName, Predicate<Class<?>> classFilter,
Predicate<String> classNameFilter) {
// unmodifiable since returned by public, non-internal method(s)
return findAllClassesInPackage(basePackageName, ClassFilter.of(classNameFilter, classFilter));
}
@API(status = INTERNAL, since = "1.1")
public static List<Class<?>> findAllClassesInPackage(String basePackageName, ClassFilter classFilter) {
return Collections.unmodifiableList(classpathScanner.scanForClassesInPackage(basePackageName, classFilter));
}
/**
* @see org.junit.platform.commons.support.ReflectionSupport#findNestedClasses(Class, Predicate)
*/
public static List<Class<?>> findNestedClasses(Class<?> clazz, Predicate<Class<?>> predicate) {
Preconditions.notNull(clazz, "Class must not be null");
Preconditions.notNull(predicate, "Predicate must not be null");
Set<Class<?>> candidates = new LinkedHashSet<>();
findNestedClasses(clazz, candidates);
return candidates.stream().filter(predicate).collect(toUnmodifiableList());
}
private static void findNestedClasses(Class<?> clazz, Set<Class<?>> candidates) {
if (clazz == Object.class || clazz == null) {
return;
}
// Candidates in current class
candidates.addAll(Arrays.asList(clazz.getDeclaredClasses()));
// Search class hierarchy
findNestedClasses(clazz.getSuperclass(), candidates);
// Search interface hierarchy
for (Class<?> ifc : clazz.getInterfaces()) {
findNestedClasses(ifc, candidates);
}
}
/**
* Get the sole declared {@link Constructor} for the supplied class.
*
* <p>Throws a {@link PreconditionViolationException} if the supplied
* class declares more than one constructor.
*
* @param clazz the class to get the constructor for
* @return the sole declared constructor; never {@code null}
* @see Class#getDeclaredConstructors()
*/
@SuppressWarnings("unchecked")
public static <T> Constructor<T> getDeclaredConstructor(Class<T> clazz) {
Preconditions.notNull(clazz, "Class must not be null");
try {
Constructor<?>[] constructors = clazz.getDeclaredConstructors();
Preconditions.condition(constructors.length == 1,
() -> String.format("Class [%s] must declare a single constructor", clazz.getName()));
return (Constructor<T>) constructors[0];
}
catch (Throwable t) {
throw ExceptionUtils.throwAsUncheckedException(getUnderlyingCause(t));
}
}
/**
* Find all constructors in the supplied class that match the supplied predicate.
*
* @param clazz the class in which to search for constructors; never {@code null}
* @param predicate the predicate to use to test for a match; never {@code null}
* @return an immutable list of all such constructors found; never {@code null}
* but potentially empty
*/
public static List<Constructor<?>> findConstructors(Class<?> clazz, Predicate<Constructor<?>> predicate) {
Preconditions.notNull(clazz, "Class must not be null");
Preconditions.notNull(predicate, "Predicate must not be null");
try {
// @formatter:off
return Arrays.stream(clazz.getDeclaredConstructors())
.filter(predicate)
.collect(toUnmodifiableList());
// @formatter:on
}
catch (Throwable t) {
throw ExceptionUtils.throwAsUncheckedException(getUnderlyingCause(t));
}
}
/**
* Find all {@linkplain Field fields} of the supplied class or interface
* that match the specified {@code predicate}, using top-down search semantics
* within the type hierarchy.
*
* <p>The results will not contain fields that are <em>hidden</em>.
*
* @param clazz the class or interface in which to find the fields; never {@code null}
* @param predicate the field filter; never {@code null}
* @return an immutable list of all such fields found; never {@code null}
* but potentially empty
* @see #findFields(Class, Predicate, HierarchyTraversalMode)
*/
public static List<Field> findFields(Class<?> clazz, Predicate<Field> predicate) {
return findFields(clazz, predicate, TOP_DOWN);
}
/**
* Find all {@linkplain Field fields} of the supplied class or interface
* that match the specified {@code predicate}.
*
* <p>The results will not contain fields that are <em>hidden</em>.
*
* @param clazz the class or interface in which to find the fields; never {@code null}
* @param predicate the field filter; never {@code null}
* @param traversalMode the hierarchy traversal mode; never {@code null}
* @return an immutable list of all such fields found; never {@code null}
* but potentially empty
* @see #findFields(Class, Predicate)
*/
public static List<Field> findFields(Class<?> clazz, Predicate<Field> predicate,
HierarchyTraversalMode traversalMode) {
Preconditions.notNull(clazz, "Class must not be null");
Preconditions.notNull(predicate, "Predicate must not be null");
Preconditions.notNull(traversalMode, "HierarchyTraversalMode must not be null");
// @formatter:off
return findAllFieldsInHierarchy(clazz, traversalMode).stream()
.filter(predicate)
// unmodifiable since returned by public, non-internal method(s)
.collect(toUnmodifiableList());
// @formatter:on
}
private static List<Field> findAllFieldsInHierarchy(Class<?> clazz, HierarchyTraversalMode traversalMode) {
Preconditions.notNull(clazz, "Class must not be null");
Preconditions.notNull(traversalMode, "HierarchyTraversalMode must not be null");
// @formatter:off
List<Field> localFields = getDeclaredFields(clazz).stream()
.filter(field -> !field.isSynthetic())
.collect(toList());
List<Field> superclassFields = getSuperclassFields(clazz, traversalMode).stream()
.filter(field -> !isFieldShadowedByLocalFields(field, localFields))
.collect(toList());
List<Field> interfaceFields = getInterfaceFields(clazz, traversalMode).stream()
.filter(field -> !isFieldShadowedByLocalFields(field, localFields))
.collect(toList());
// @formatter:on
List<Field> fields = new ArrayList<>();
if (traversalMode == TOP_DOWN) {
fields.addAll(superclassFields);
fields.addAll(interfaceFields);
}
fields.addAll(localFields);
if (traversalMode == BOTTOM_UP) {
fields.addAll(interfaceFields);
fields.addAll(superclassFields);
}
return fields;
}
/**
* Determine if a {@link Method} matching the supplied {@link Predicate}
* is present within the type hierarchy of the specified class, beginning
* with the specified class or interface and traversing up the type
* hierarchy until such a method is found or the type hierarchy is exhausted.
*
* @param clazz the class or interface in which to find the method; never
* {@code null}
* @param predicate the predicate to use to test for a match; never
* {@code null}
* @return {@code true} if such a method is present
* @see #findMethod(Class, String, String)
* @see #findMethod(Class, String, Class...)
*/
public static boolean isMethodPresent(Class<?> clazz, Predicate<Method> predicate) {
Preconditions.notNull(clazz, "Class must not be null");
Preconditions.notNull(predicate, "Predicate must not be null");
return findMethod(clazz, predicate).isPresent();
}
/**
* Get the {@link Method} in the specified class with the specified name
* and parameter types.
*
* <p>This method delegates to {@link Class#getMethod(String, Class...)} but
* swallows any exception thrown.
*
* @param clazz the class in which to search for the method; never {@code null}
* @param methodName the name of the method to get; never {@code null} or blank
* @param parameterTypes the parameter types of the method; may be {@code null}
* or empty
* @return an {@code Optional} containing the method; never {@code null} but
* empty if the invocation of {@code Class#getMethod()} throws a
* {@link NoSuchMethodException}
*/
static Optional<Method> getMethod(Class<?> clazz, String methodName, Class<?>... parameterTypes) {
Preconditions.notNull(clazz, "Class must not be null");
Preconditions.notBlank(methodName, "Method name must not be null or blank");
try {
return Optional.ofNullable(clazz.getMethod(methodName, parameterTypes));
}
catch (NoSuchMethodException ex) {
return Optional.empty();
}
catch (Throwable t) {
throw ExceptionUtils.throwAsUncheckedException(t);
}
}
/**
* @see org.junit.platform.commons.support.ReflectionSupport#findMethod(Class, String, String)
*/
public static Optional<Method> findMethod(Class<?> clazz, String methodName, String parameterTypeNames) {
return findMethod(clazz, methodName, resolveParameterTypes(clazz, methodName, parameterTypeNames));
}
private static Class<?>[] resolveParameterTypes(Class<?> clazz, String methodName, String parameterTypeNames) {
if (StringUtils.isBlank(parameterTypeNames)) {
return EMPTY_CLASS_ARRAY;
}
// @formatter:off
return Arrays.stream(parameterTypeNames.split(","))
.map(typeName -> loadRequiredParameterType(clazz, methodName, typeName))
.toArray(Class[]::new);
// @formatter:on
}
private static Class<?> loadRequiredParameterType(Class<?> clazz, String methodName, String typeName) {
return loadClass(typeName).orElseThrow(
() -> new JUnitException(String.format("Failed to load parameter type [%s] for method [%s] in class [%s].",
typeName, methodName, clazz.getName())));
}
/**
* @see org.junit.platform.commons.support.ReflectionSupport#findMethod(Class, String, Class...)
*/
public static Optional<Method> findMethod(Class<?> clazz, String methodName, Class<?>... parameterTypes) {
Preconditions.notNull(clazz, "Class must not be null");
Preconditions.notBlank(methodName, "Method name must not be null or blank");
Preconditions.notNull(parameterTypes, "Parameter types array must not be null");
Preconditions.containsNoNullElements(parameterTypes, "Individual parameter types must not be null");
return findMethod(clazz, method -> hasCompatibleSignature(method, methodName, parameterTypes));
}
private static Optional<Method> findMethod(Class<?> clazz, Predicate<Method> predicate) {
Preconditions.notNull(clazz, "Class must not be null");
Preconditions.notNull(predicate, "Predicate must not be null");
for (Class<?> current = clazz; current != null && current != Object.class; current = current.getSuperclass()) {
// Search for match in current type
List<Method> methods = current.isInterface() ? getMethods(current) : getDeclaredMethods(current, BOTTOM_UP);
for (Method method : methods) {
if (predicate.test(method)) {
return Optional.of(method);
}
}
// Search for match in interfaces implemented by current type
for (Class<?> ifc : current.getInterfaces()) {
Optional<Method> optional = findMethod(ifc, predicate);
if (optional.isPresent()) {
return optional;
}
}
}
return Optional.empty();
}
/**
* Find all {@linkplain Method methods} of the supplied class or interface
* that match the specified {@code predicate}, using top-down search semantics
* within the type hierarchy.
*
* <p>The results will not contain instance methods that are <em>overridden</em>
* or {@code static} methods that are <em>hidden</em>.
*
* @param clazz the class or interface in which to find the methods; never {@code null}
* @param predicate the method filter; never {@code null}
* @return an immutable list of all such methods found; never {@code null}
* @see HierarchyTraversalMode#TOP_DOWN
* @see #findMethods(Class, Predicate, HierarchyTraversalMode)
*/
public static List<Method> findMethods(Class<?> clazz, Predicate<Method> predicate) {
return findMethods(clazz, predicate, TOP_DOWN);
}
/**
* @see org.junit.platform.commons.support.ReflectionSupport#findMethods(Class, Predicate, org.junit.platform.commons.support.HierarchyTraversalMode)
*/
public static List<Method> findMethods(Class<?> clazz, Predicate<Method> predicate,
HierarchyTraversalMode traversalMode) {
Preconditions.notNull(clazz, "Class must not be null");
Preconditions.notNull(predicate, "Predicate must not be null");
Preconditions.notNull(traversalMode, "HierarchyTraversalMode must not be null");
// @formatter:off
return findAllMethodsInHierarchy(clazz, traversalMode).stream()
.filter(predicate)
// unmodifiable since returned by public, non-internal method(s)
.collect(toUnmodifiableList());
// @formatter:on