-
Notifications
You must be signed in to change notification settings - Fork 108
/
ReflectionUtils.java
1461 lines (1325 loc) · 60.2 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
package com.cedarsoftware.util;
import java.io.ByteArrayInputStream;
import java.io.DataInputStream;
import java.io.IOException;
import java.io.InputStream;
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.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.HashSet;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Set;
import java.util.stream.Collectors;
import static com.cedarsoftware.util.ExceptionUtilities.safelyIgnoreException;
/**
* Utilities to simplify writing reflective code as well as improve performance of reflective operations like
* method and annotation lookups.
*
* @author John DeRegnaucourt ([email protected])
* <br>
* Copyright (c) Cedar Software LLC
* <br><br>
* 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
* <br><br>
* <a href="http://www.apache.org/licenses/LICENSE-2.0">License</a>
* <br><br>
* 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.
*/
public final class ReflectionUtils {
private static final int CACHE_SIZE = 1000;
private static volatile Map<ConstructorCacheKey, Constructor<?>> CONSTRUCTOR_CACHE = new LRUCache<>(CACHE_SIZE);
private static volatile Map<MethodCacheKey, Method> METHOD_CACHE = new LRUCache<>(CACHE_SIZE);
private static volatile Map<FieldsCacheKey, Collection<Field>> FIELDS_CACHE = new LRUCache<>(CACHE_SIZE);
private static volatile Map<FieldNameCacheKey, Field> FIELD_NAME_CACHE = new LRUCache<>(CACHE_SIZE * 10);
private static volatile Map<ClassAnnotationCacheKey, Annotation> CLASS_ANNOTATION_CACHE = new LRUCache<>(CACHE_SIZE);
private static volatile Map<MethodAnnotationCacheKey, Annotation> METHOD_ANNOTATION_CACHE = new LRUCache<>(CACHE_SIZE);
/**
* Sets a custom cache implementation for method lookups.
* <p>
* This method allows switching out the default LRUCache implementation with a custom
* cache implementation. The provided cache must be thread-safe and should implement
* the Map interface. This method is typically called once during application initialization.
* </p>
*
* @param cache The custom cache implementation to use for storing method lookups.
* Must be thread-safe and implement Map interface.
*/
public static void setMethodCache(Map<Object, Method> cache) {
METHOD_CACHE = (Map) cache;
}
/**
* Sets a custom cache implementation for field lookups.
* <p>
* This method allows switching out the default LRUCache implementation with a custom
* cache implementation. The provided cache must be thread-safe and should implement
* the Map interface. This method is typically called once during application initialization.
* </p>
*
* @param cache The custom cache implementation to use for storing field lookups.
* Must be thread-safe and implement Map interface.
*/
public static void setClassFieldsCache(Map<Object, Collection<Field>> cache) {
FIELDS_CACHE = (Map) cache;
}
/**
* Sets a custom cache implementation for field lookups.
* <p>
* This method allows switching out the default LRUCache implementation with a custom
* cache implementation. The provided cache must be thread-safe and should implement
* the Map interface. This method is typically called once during application initialization.
* </p>
*
* @param cache The custom cache implementation to use for storing field lookups.
* Must be thread-safe and implement Map interface.
*/
public static void setFieldCache(Map<Object, Field> cache) {
FIELD_NAME_CACHE = (Map) cache;
}
/**
* Sets a custom cache implementation for class annotation lookups.
* <p>
* This method allows switching out the default LRUCache implementation with a custom
* cache implementation. The provided cache must be thread-safe and should implement
* the Map interface. This method is typically called once during application initialization.
* </p>
*
* @param cache The custom cache implementation to use for storing class annotation lookups.
* Must be thread-safe and implement Map interface.
*/
public static void setClassAnnotationCache(Map<Object, Annotation> cache) {
CLASS_ANNOTATION_CACHE = (Map) cache;
}
/**
* Sets a custom cache implementation for method annotation lookups.
* <p>
* This method allows switching out the default LRUCache implementation with a custom
* cache implementation. The provided cache must be thread-safe and should implement
* the Map interface. This method is typically called once during application initialization.
* </p>
*
* @param cache The custom cache implementation to use for storing method annotation lookups.
* Must be thread-safe and implement Map interface.
*/
public static void setMethodAnnotationCache(Map<Object, Annotation> cache) {
METHOD_ANNOTATION_CACHE = (Map) cache;
}
/**
* Sets a custom cache implementation for constructor lookups.
* <p>
* This method allows switching out the default LRUCache implementation with a custom
* cache implementation. The provided cache must be thread-safe and should implement
* the Map interface. This method is typically called once during application initialization.
* </p>
*
* @param cache The custom cache implementation to use for storing constructor lookups.
* Must be thread-safe and implement Map interface.
*/
public static void setConstructorCache(Map<Object, Constructor<?>> cache) {
CONSTRUCTOR_CACHE = (Map) cache;
}
private ReflectionUtils() { }
private static final class ClassAnnotationCacheKey {
private final String classLoaderName;
private final String className;
private final String annotationClassName;
private final int hash;
ClassAnnotationCacheKey(Class<?> clazz, Class<? extends Annotation> annotationClass) {
this.classLoaderName = getClassLoaderName(clazz);
this.className = clazz.getName();
this.annotationClassName = annotationClass.getName();
this.hash = Objects.hash(classLoaderName, className, annotationClassName);
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (!(o instanceof ClassAnnotationCacheKey)) return false;
ClassAnnotationCacheKey that = (ClassAnnotationCacheKey) o;
return Objects.equals(classLoaderName, that.classLoaderName) &&
Objects.equals(className, that.className) &&
Objects.equals(annotationClassName, that.annotationClassName);
}
@Override
public int hashCode() {
return hash;
}
}
private static final class MethodAnnotationCacheKey {
private final String classLoaderName;
private final String className;
private final String methodName;
private final String parameterTypes;
private final String annotationClassName;
private final int hash;
MethodAnnotationCacheKey(Method method, Class<? extends Annotation> annotationClass) {
Class<?> declaringClass = method.getDeclaringClass();
this.classLoaderName = getClassLoaderName(declaringClass);
this.className = declaringClass.getName();
this.methodName = method.getName();
this.parameterTypes = makeParamKey(method.getParameterTypes());
this.annotationClassName = annotationClass.getName();
this.hash = Objects.hash(classLoaderName, className, methodName, parameterTypes, annotationClassName);
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (!(o instanceof MethodAnnotationCacheKey)) return false;
MethodAnnotationCacheKey that = (MethodAnnotationCacheKey) o;
return Objects.equals(classLoaderName, that.classLoaderName) &&
Objects.equals(className, that.className) &&
Objects.equals(methodName, that.methodName) &&
Objects.equals(parameterTypes, that.parameterTypes) &&
Objects.equals(annotationClassName, that.annotationClassName);
}
@Override
public int hashCode() {
return hash;
}
}
private static final class ConstructorCacheKey {
private final String classLoaderName;
private final String className;
private final String parameterTypes;
private final int hash;
ConstructorCacheKey(Class<?> clazz, Class<?>... types) {
this.classLoaderName = getClassLoaderName(clazz);
this.className = clazz.getName();
this.parameterTypes = makeParamKey(types);
this.hash = Objects.hash(classLoaderName, className, parameterTypes);
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (!(o instanceof ConstructorCacheKey)) return false;
ConstructorCacheKey that = (ConstructorCacheKey) o;
return Objects.equals(classLoaderName, that.classLoaderName) &&
Objects.equals(className, that.className) &&
Objects.equals(parameterTypes, that.parameterTypes);
}
@Override
public int hashCode() {
return hash;
}
}
private static final class FieldNameCacheKey {
private final String classLoaderName;
private final String className;
private final String fieldName;
private final int hash;
FieldNameCacheKey(Class<?> clazz, String fieldName) {
this.classLoaderName = getClassLoaderName(clazz);
this.className = clazz.getName();
this.fieldName = fieldName;
this.hash = Objects.hash(classLoaderName, className, fieldName);
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (!(o instanceof FieldNameCacheKey)) return false;
FieldNameCacheKey that = (FieldNameCacheKey) o;
return Objects.equals(classLoaderName, that.classLoaderName) &&
Objects.equals(className, that.className) &&
Objects.equals(fieldName, that.fieldName);
}
@Override
public int hashCode() {
return hash;
}
}
private static final class FieldsCacheKey {
private final String classLoaderName;
private final String className;
private final boolean deep;
private final int hash;
FieldsCacheKey(Class<?> clazz, boolean deep) {
this.classLoaderName = getClassLoaderName(clazz);
this.className = clazz.getName();
this.deep = deep;
this.hash = Objects.hash(classLoaderName, className, deep);
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (!(o instanceof FieldsCacheKey)) return false;
FieldsCacheKey other = (FieldsCacheKey) o;
return deep == other.deep &&
Objects.equals(classLoaderName, other.classLoaderName) &&
Objects.equals(className, other.className);
}
@Override
public int hashCode() {
return hash;
}
}
public static class MethodCacheKey {
private final String classLoaderName;
private final String className;
private final String methodName;
private final String parameterTypes;
private final int hash;
public MethodCacheKey(Class<?> clazz, String methodName, Class<?>... types) {
this.classLoaderName = getClassLoaderName(clazz);
this.className = clazz.getName();
this.methodName = methodName;
this.parameterTypes = makeParamKey(types);
// Pre-compute hash code
this.hash = Objects.hash(classLoaderName, className, methodName, parameterTypes);
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (!(o instanceof MethodCacheKey)) return false;
MethodCacheKey that = (MethodCacheKey) o;
return Objects.equals(classLoaderName, that.classLoaderName) &&
Objects.equals(className, that.className) &&
Objects.equals(methodName, that.methodName) &&
Objects.equals(parameterTypes, that.parameterTypes);
}
@Override
public int hashCode() {
return hash;
}
}
/**
* Searches for a specific annotation on a class, examining the entire inheritance hierarchy.
* Results (including misses) are cached for performance.
* <p>
* This method performs an exhaustive search through:
* <ul>
* <li>The class itself</li>
* <li>All superclasses</li>
* <li>All implemented interfaces</li>
* <li>All super-interfaces</li>
* </ul>
* <p>
* Key behaviors:
* <ul>
* <li>Caches both found annotations and misses (nulls)</li>
* <li>Handles different classloaders correctly</li>
* <li>Uses depth-first search through the inheritance hierarchy</li>
* <li>Prevents circular reference issues</li>
* <li>Returns the first matching annotation found</li>
* <li>Thread-safe implementation</li>
* </ul>
* <p>
* Example usage:
* <pre>
* JsonObject anno = ReflectionUtils.getClassAnnotation(MyClass.class, JsonObject.class);
* if (anno != null) {
* // Process annotation...
* }
* </pre>
*
* @param classToCheck The class to search for the annotation
* @param annoClass The annotation class to search for
* @param <T> The type of the annotation
* @return The annotation if found, null otherwise
* @throws IllegalArgumentException if either classToCheck or annoClass is null
*/
public static <T extends Annotation> T getClassAnnotation(final Class<?> classToCheck, final Class<T> annoClass) {
if (classToCheck == null) {
return null; // legacy behavior, not changing now.
}
Convention.throwIfNull(annoClass, "annotation class cannot be null");
ClassAnnotationCacheKey key = new ClassAnnotationCacheKey(classToCheck, annoClass);
// Check cache first
Annotation cached = CLASS_ANNOTATION_CACHE.get(key);
if (cached != null || CLASS_ANNOTATION_CACHE.containsKey(key)) {
return (T) cached;
}
// Not in cache, do the lookup
T found = findClassAnnotation(classToCheck, annoClass);
// Cache the result (even if null)
CLASS_ANNOTATION_CACHE.put(key, found);
return found;
}
private static <T extends Annotation> T findClassAnnotation(Class<?> classToCheck, Class<T> annoClass) {
final Set<Class<?>> visited = new HashSet<>();
final LinkedList<Class<?>> stack = new LinkedList<>();
stack.add(classToCheck);
while (!stack.isEmpty()) {
Class<?> classToChk = stack.pop();
if (classToChk == null || visited.contains(classToChk)) {
continue;
}
visited.add(classToChk);
T a = classToChk.getAnnotation(annoClass);
if (a != null) {
return a;
}
stack.push(classToChk.getSuperclass());
addInterfaces(classToChk, stack);
}
return null;
}
private static void addInterfaces(final Class<?> classToCheck, final LinkedList<Class<?>> stack) {
for (Class<?> interFace : classToCheck.getInterfaces()) {
stack.push(interFace);
}
}
/**
* Searches for a specific annotation on a method, examining the entire inheritance hierarchy.
* Results (including misses) are cached for performance.
* <p>
* This method performs an exhaustive search through:
* <ul>
* <li>The method in the declaring class</li>
* <li>Matching methods in all superclasses</li>
* <li>Matching methods in all implemented interfaces</li>
* <li>Matching methods in all super-interfaces</li>
* </ul>
* <p>
* Key behaviors:
* <ul>
* <li>Caches both found annotations and misses (nulls)</li>
* <li>Handles different classloaders correctly</li>
* <li>Uses depth-first search through the inheritance hierarchy</li>
* <li>Matches methods by name and parameter types</li>
* <li>Prevents circular reference issues</li>
* <li>Returns the first matching annotation found</li>
* <li>Thread-safe implementation</li>
* </ul>
* <p>
* Example usage:
* <pre>
* Method method = obj.getClass().getMethod("processData", String.class);
* JsonProperty anno = ReflectionUtils.getMethodAnnotation(method, JsonProperty.class);
* if (anno != null) {
* // Process annotation...
* }
* </pre>
*
* @param method The method to search for the annotation
* @param annoClass The annotation class to search for
* @param <T> The type of the annotation
* @return The annotation if found, null otherwise
* @throws IllegalArgumentException if either method or annoClass is null
*/
public static <T extends Annotation> T getMethodAnnotation(final Method method, final Class<T> annoClass) {
Convention.throwIfNull(method, "method cannot be null");
Convention.throwIfNull(annoClass, "annotation class cannot be null");
MethodAnnotationCacheKey key = new MethodAnnotationCacheKey(method, annoClass);
// Check cache first
Annotation cached = METHOD_ANNOTATION_CACHE.get(key);
if (cached != null || METHOD_ANNOTATION_CACHE.containsKey(key)) {
return (T) cached;
}
// Search through class hierarchy
Class<?> currentClass = method.getDeclaringClass();
while (currentClass != null) {
try {
Method currentMethod = currentClass.getDeclaredMethod(
method.getName(),
method.getParameterTypes()
);
T annotation = currentMethod.getAnnotation(annoClass);
if (annotation != null) {
METHOD_ANNOTATION_CACHE.put(key, annotation);
return annotation;
}
} catch (NoSuchMethodException ignored) {
// Method not found in current class, continue up hierarchy
}
currentClass = currentClass.getSuperclass();
}
// Also check interfaces
for (Class<?> iface : method.getDeclaringClass().getInterfaces()) {
try {
Method ifaceMethod = iface.getMethod(
method.getName(),
method.getParameterTypes()
);
T annotation = ifaceMethod.getAnnotation(annoClass);
if (annotation != null) {
METHOD_ANNOTATION_CACHE.put(key, annotation);
return annotation;
}
} catch (NoSuchMethodException ignored) {
// Method not found in interface
}
}
// Cache the miss
METHOD_ANNOTATION_CACHE.put(key, null);
return null;
}
/**
* Retrieves a specific field from a class by name, searching through the entire class hierarchy
* (including superclasses). Results are cached for performance.
* <p>
* This method:
* <ul>
* <li>Searches through all fields (public, protected, package, private)</li>
* <li>Includes fields from superclasses</li>
* <li>Excludes static fields</li>
* <li>Makes non-public fields accessible</li>
* <li>Caches results (including misses) for performance</li>
* </ul>
* <p>
* Example usage:
* <pre>
* Field nameField = ReflectionUtils.getField(Employee.class, "name");
* if (nameField != null) {
* nameField.set(employee, "John");
* }
* </pre>
*
* @param c The class to search for the field
* @param fieldName The name of the field to find
* @return The Field object if found, null if the field doesn't exist
* @throws IllegalArgumentException if either the class or fieldName is null
*/
public static Field getField(Class<?> c, String fieldName) {
Convention.throwIfNull(c, "class cannot be null");
Convention.throwIfNull(fieldName, "fieldName cannot be null");
FieldNameCacheKey key = new FieldNameCacheKey(c, fieldName);
// Check if we already cached this field lookup
Field cachedField = FIELD_NAME_CACHE.get(key);
if (cachedField != null || FIELD_NAME_CACHE.containsKey(key)) { // Handle null field case (caches misses)
return cachedField;
}
// Not in cache, do the linear search
Collection<Field> fields = getAllDeclaredFields(c);
Field found = null;
for (Field field : fields) {
if (fieldName.equals(field.getName())) {
found = field;
break;
}
}
// Cache the result (even if null)
FIELD_NAME_CACHE.put(key, found);
return found;
}
/**
* Retrieves the declared fields of a class, with sophisticated filtering and caching.
* This method provides direct field access with careful handling of special cases.
* <p>
* Field filtering:
* <ul>
* <li>Returns only fields declared directly on the specified class (not from superclasses)</li>
* <li>Excludes static fields</li>
* <li>Excludes internal enum fields ("internal" and "ENUM$VALUES")</li>
* <li>Excludes enum base class fields ("hash" and "ordinal")</li>
* <li>Excludes Groovy's metaClass field</li>
* </ul>
* <p>
* Included fields:
* <ul>
* <li>All instance fields (public, protected, package, private)</li>
* <li>Transient fields</li>
* <li>Synthetic fields for inner classes (e.g., "$this" reference to enclosing class)</li>
* <li>Compiler-generated fields for anonymous classes and lambdas</li>
* </ul>
* <p>
* Key behaviors:
* <ul>
* <li>Attempts to make non-public fields accessible</li>
* <li>Caches both successful lookups and misses</li>
* <li>Returns an unmodifiable List to prevent modification</li>
* <li>Handles different classloaders correctly</li>
* <li>Thread-safe implementation</li>
* <li>Maintains consistent order of fields</li>
* </ul>
* <p>
* Note: For fields from the entire class hierarchy, use {@link #getAllDeclaredFields(Class)} instead.
* <p>
* Example usage:
* <pre>
* List<Field> fields = ReflectionUtils.getDeclaredFields(MyClass.class);
* for (Field field : fields) {
* // Process each field...
* }
* </pre>
*
* @param c The class whose declared fields are to be retrieved
* @return An unmodifiable list of the class's declared fields
* @throws IllegalArgumentException if the class is null
* @see #getAllDeclaredFields(Class) For retrieving fields from the entire class hierarchy
*/
public static List<Field> getDeclaredFields(final Class<?> c) {
Convention.throwIfNull(c, "class cannot be null");
FieldsCacheKey key = new FieldsCacheKey(c, false);
Collection<Field> cached = FIELDS_CACHE.get(key);
if (cached != null || FIELDS_CACHE.containsKey(key)) { // Cache misses so we don't retry over and over
return (List<Field>) cached;
}
Field[] fields = c.getDeclaredFields();
List<Field> list = new ArrayList<>(fields.length); // do not change from being List
for (Field field : fields) {
String fieldName = field.getName();
if (Modifier.isStatic(field.getModifiers()) ||
(field.getDeclaringClass().isEnum() && ("internal".equals(fieldName) || "ENUM$VALUES".equals(fieldName))) ||
("metaClass".equals(fieldName) && "groovy.lang.MetaClass".equals(field.getType().getName())) ||
(field.getDeclaringClass().isAssignableFrom(Enum.class) && ("hash".equals(fieldName) || "ordinal".equals(fieldName)))) {
continue;
}
if (!Modifier.isPublic(field.getModifiers())) {
try {
field.setAccessible(true);
} catch(Exception ignored) { }
}
list.add(field);
}
List<Field> unmodifiableFields = Collections.unmodifiableList(list);
FIELDS_CACHE.put(key, unmodifiableFields);
return unmodifiableFields;
}
/**
* Retrieves all fields from a class and its complete inheritance hierarchy, with
* sophisticated filtering and caching. This method provides comprehensive field access
* across the entire class hierarchy up to Object.
* <p>
* Field filtering:
* <ul>
* <li>Includes fields from the specified class and all superclasses</li>
* <li>Excludes static fields</li>
* <li>Excludes internal enum fields ("internal" and "ENUM$VALUES")</li>
* <li>Excludes enum base class fields ("hash" and "ordinal")</li>
* <li>Excludes Groovy's metaClass field</li>
* </ul>
* <p>
* Included fields:
* <ul>
* <li>All instance fields (public, protected, package, private)</li>
* <li>Fields from all superclasses up to Object</li>
* <li>Transient fields</li>
* <li>Synthetic fields for inner classes (e.g., "$this" reference to enclosing class)</li>
* <li>Compiler-generated fields for anonymous classes and lambdas</li>
* </ul>
* <p>
* Key behaviors:
* <ul>
* <li>Attempts to make non-public fields accessible</li>
* <li>Caches both successful lookups and misses</li>
* <li>Returns an unmodifiable List to prevent modification</li>
* <li>Handles different classloaders correctly</li>
* <li>Thread-safe implementation</li>
* <li>Maintains consistent order of fields (subclass fields before superclass fields)</li>
* <li>Uses recursive caching strategy for optimal performance</li>
* </ul>
* <p>
* Example usage:
* <pre>
* List<Field> allFields = ReflectionUtils.getAllDeclaredFields(MyClass.class);
* for (Field field : allFields) {
* // Process each field, including inherited fields...
* }
* </pre>
*
* @param c The class whose complete field hierarchy is to be retrieved
* @return An unmodifiable list of all fields in the class hierarchy
* @throws IllegalArgumentException if the class is null
* @see #getDeclaredFields(Class) For retrieving fields from just the specified class
*/
public static List<Field> getAllDeclaredFields(final Class<?> c) {
Convention.throwIfNull(c, "class cannot be null");
FieldsCacheKey key = new FieldsCacheKey(c, true);
Collection<Field> cached = FIELDS_CACHE.get(key);
if (cached != null || FIELDS_CACHE.containsKey(key)) { // Cache misses so we do not retry over and over
return (List<Field>) cached;
}
List<Field> allFields = new ArrayList<>();
Class<?> current = c;
while (current != null) {
allFields.addAll(getDeclaredFields(current));
current = current.getSuperclass();
}
List<Field> unmodifiableFields = Collections.unmodifiableList(allFields);
FIELDS_CACHE.put(key, unmodifiableFields);
return unmodifiableFields;
}
/**
* Return all Fields from a class (including inherited), mapped by String field name
* to java.lang.reflect.Field. This method uses getDeclaredFields(Class) to obtain
* the methods from a class, therefore it will have the same field inclusion rules
* as getAllDeclaredFields().
* <p>
* Additional Field mapping rules for String key names:
* <ul>
* <li>Simple field names (e.g., "name") are used when no collision exists</li>
* <li>Qualified names (e.g., "com.example.Parent.name") are used to resolve collisions</li>
* <li>Child class fields take precedence for simple name mapping</li>
* <li>Parent class fields use fully qualified names when shadowed</li>
* </ul>
* <p>
*
* @param c Class whose fields are being fetched
* @return Map of filtered fields on the Class, keyed by String field name to Field
* @throws IllegalArgumentException if the class is null
*/
public static Map<String, Field> getAllDeclaredFieldsMap(Class<?> c) {
Convention.throwIfNull(c, "class cannot be null");
Map<String, Field> fieldMap = new LinkedHashMap<>();
Collection<Field> fields = getAllDeclaredFields(c); // Uses FIELDS_CACHE internally
for (Field field : fields) {
String fieldName = field.getName();
if (fieldMap.containsKey(fieldName)) { // Can happen when parent and child class both have private field with same name
fieldMap.put(field.getDeclaringClass().getName() + '.' + fieldName, field);
} else {
fieldMap.put(fieldName, field);
}
}
return fieldMap;
}
/**
* @deprecated As of 2.x.x, replaced by {@link #getAllDeclaredFields(Class)}.
* Note that getAllDeclaredFields() includes transient fields and synthetic fields
* (like "$this"). If you need the old behavior, filter the additional fields:
* <pre>
* List<Field> fields = getAllDeclaredFields(clazz).stream()
* .filter(f -> !Modifier.isTransient(f.getModifiers()))
* .filter(f -> !f.getName().startsWith("this$"))
* .collect(Collectors.toList());
* </pre>
* This method will be removed in 3.0.0.
*/
@Deprecated
public static Collection<Field> getDeepDeclaredFields(Class<?> c) {
Convention.throwIfNull(c, "Class cannot be null");
FieldsCacheKey key = new FieldsCacheKey(c, true);
Collection<Field> cached = FIELDS_CACHE.get(key);
if (cached != null || FIELDS_CACHE.containsKey(key)) { // Cache null too
// Filter the cached fields according to the old behavior
return cached.stream()
.filter(f -> !Modifier.isTransient(f.getModifiers()))
.filter(f -> !f.getName().startsWith("this$"))
.collect(Collectors.toList());
}
// If not in cache, getAllDeclaredFields will do the work and cache it
Collection<Field> allFields = getAllDeclaredFields(c);
// Filter and return according to old behavior
return Collections.unmodifiableCollection(allFields.stream()
.filter(f -> !Modifier.isTransient(f.getModifiers()))
.filter(f -> !f.getName().startsWith("this$"))
.collect(Collectors.toList()));
}
/**
* Return all Fields from a class (including inherited), mapped by String field name
* to java.lang.reflect.Field, excluding synthetic "$this" fields and transient fields.
* <p>
* Field mapping rules:
* <ul>
* <li>Simple field names (e.g., "name") are used when no collision exists</li>
* <li>Qualified names (e.g., "com.example.Parent.name") are used to resolve collisions</li>
* <li>Child class fields take precedence for simple name mapping</li>
* <li>Parent class fields use fully qualified names when shadowed</li>
* </ul>
* <p>
* Excluded fields:
* <ul>
* <li>Transient fields</li>
* <li>Synthetic "$this" fields for inner classes</li>
* <li>Other synthetic fields</li>
* </ul>
*
* @deprecated As of 2.x.x, replaced by {@link #getAllDeclaredFieldsMap(Class)}.
* If you need a map of fields excluding transient and synthetic fields:
* <pre>
* Map<String, Field> fieldMap = getAllDeclaredFields(clazz).stream()
* .filter(f -> !Modifier.isTransient(f.getModifiers()))
* .filter(f -> !f.getName().startsWith("this$"))
* .collect(Collectors.toMap(
* field -> {
* String name = field.getName();
* return seen.add(name) ? name :
* field.getDeclaringClass().getName() + "." + name;
* },
* field -> field,
* (existing, replacement) -> replacement,
* LinkedHashMap::new
* ));
* </pre>
* This method will be removed in 3.0.0 or later.
*
* @param c Class whose fields are being fetched
* @return Map of filtered fields on the Class, keyed by String field name to Field
* @throws IllegalArgumentException if the class is null
*/
@Deprecated
public static Map<String, Field> getDeepDeclaredFieldMap(Class<?> c) {
Convention.throwIfNull(c, "class cannot be null");
Map<String, Field> fieldMap = new LinkedHashMap<>();
Collection<Field> fields = getAllDeclaredFields(c); // Uses FIELDS_CACHE internally
for (Field field : fields) {
// Skip transient and synthetic fields
if (Modifier.isTransient(field.getModifiers()) ||
field.getName().startsWith("this$")) {
continue;
}
String fieldName = field.getName();
if (fieldMap.containsKey(fieldName)) { // Can happen when parent and child class both have private field with same name
fieldMap.put(field.getDeclaringClass().getName() + '.' + fieldName, field);
} else {
fieldMap.put(fieldName, field);
}
}
return fieldMap;
}
/**
* @deprecated As of 2.x.x, replaced by {@link #getAllDeclaredFields(Class)}.
* Note that getAllDeclaredFields() includes transient fields and synthetic fields
* (like "$this"). If you need the old behavior, filter the additional fields:
* <pre>
* List<Field> fields = getAllDeclaredFields(clazz).stream()
* .filter(f -> !Modifier.isTransient(f.getModifiers()))
* .filter(f -> !f.getName().startsWith("this$"))
* .collect(Collectors.toList());
* </pre>
* This method will be removed in 3.0.0 or soon after.
*/
@Deprecated
public static void getDeclaredFields(Class<?> c, Collection<Field> fields) {
try {
Field[] local = c.getDeclaredFields();
for (Field field : local) {
int modifiers = field.getModifiers();
if (Modifier.isStatic(modifiers) || Modifier.isTransient(modifiers)) {
continue;
}
String fieldName = field.getName();
if ("metaClass".equals(fieldName) && "groovy.lang.MetaClass".equals(field.getType().getName())) {
continue;
}
if (fieldName.startsWith("this$")) {
continue;
}
if (Modifier.isPublic(modifiers)) {
fields.add(field);
} else {
try {
field.setAccessible(true);
} catch(Exception ignored) { }
fields.add(field);
}
}
} catch (Throwable t) {
safelyIgnoreException(t);
}
}
/**
* Simplifies reflective method invocation by wrapping checked exceptions into runtime exceptions.
* This method provides a cleaner API for reflection-based method calls.
* <p>
* Key features:
* <ul>
* <li>Converts checked exceptions to runtime exceptions</li>
* <li>Preserves the original exception cause</li>
* <li>Provides clear error messages</li>
* <li>Handles null checking for both method and instance</li>
* </ul>
* <p>
* Exception handling:
* <ul>
* <li>IllegalAccessException → RuntimeException</li>
* <li>InvocationTargetException → RuntimeException (with target exception)</li>
* <li>Null method → IllegalArgumentException</li>
* <li>Null instance → IllegalArgumentException</li>
* </ul>
* <p>
* Example usage:
* <pre>
* Method method = ReflectionUtils.getMethod(obj.getClass(), "processData", String.class);
* Object result = ReflectionUtils.call(obj, method, "input data");
*
* // No need for try-catch blocks for checked exceptions
* // Just handle RuntimeException if needed
* </pre>
*
* @param instance The object instance on which to call the method
* @param method The Method object representing the method to call
* @param args The arguments to pass to the method (may be empty)
* @return The result of the method invocation, or null for void methods
* @throws IllegalArgumentException if either method or instance is null
* @throws RuntimeException if the method is inaccessible or throws an exception
* @see Method#invoke(Object, Object...) For the underlying reflection mechanism
*/
public static Object call(Object instance, Method method, Object... args) {
if (method == null) {
String className = (instance == null) ? "null instance" : instance.getClass().getName();
throw new IllegalArgumentException("null Method passed to ReflectionUtils.call() on instance of type: " + className);
}
if (instance == null) {
throw new IllegalArgumentException("Cannot call [" + method.getName() + "()] on a null object.");
}
try {
return method.invoke(instance, args);
} catch (IllegalAccessException e) {
throw new RuntimeException("IllegalAccessException occurred attempting to reflectively call method: " + method.getName() + "()", e);
} catch (InvocationTargetException e) {
throw new RuntimeException("Exception thrown inside reflectively called method: " + method.getName() + "()", e.getTargetException());
}
}
/**
* Provides a simplified, cached reflection API for method invocation using method name.
* This method combines method lookup and invocation in one step, with results cached
* for performance.
* <p>
* Key features:
* <ul>
* <li>Caches method lookups for improved performance</li>
* <li>Handles different classloaders correctly</li>
* <li>Converts checked exceptions to runtime exceptions</li>
* <li>Caches both successful lookups and misses</li>
* <li>Thread-safe implementation</li>
* </ul>
* <p>
* Limitations:
* <ul>
* <li>Does not distinguish between overloaded methods with same parameter count</li>
* <li>Only matches by method name and parameter count</li>
* <li>Always selects the first matching method found</li>
* <li>Only finds public methods</li>
* </ul>
* <p>
* Exception handling:
* <ul>
* <li>Method not found → IllegalArgumentException</li>
* <li>IllegalAccessException → RuntimeException</li>
* <li>InvocationTargetException → RuntimeException (with target exception)</li>
* <li>Null instance/methodName → IllegalArgumentException</li>
* </ul>
* <p>
* Example usage:
* <pre>
* // Simple case - no method overloading
* Object result = ReflectionUtils.call(myObject, "processData", "input");
*
* // For overloaded methods, use the more specific call() method:
* Method specific = ReflectionUtils.getMethod(myObject.getClass(), "processData", String.class);
* Object result = ReflectionUtils.call(myObject, specific, "input");
* </pre>
*
* @param instance The object instance on which to call the method
* @param methodName The name of the method to call
* @param args The arguments to pass to the method (may be empty)
* @return The result of the method invocation, or null for void methods
* @throws IllegalArgumentException if the method cannot be found, or if instance/methodName is null
* @throws RuntimeException if the method is inaccessible or throws an exception
* @see #call(Object, Method, Object...) For handling overloaded methods
* @see #getMethod(Class, String, Class...) For explicit method lookup with parameter types
*/
public static Object call(Object instance, String methodName, Object... args) {