-
Notifications
You must be signed in to change notification settings - Fork 3.5k
/
ReflectHelper.java
1004 lines (897 loc) · 32.2 KB
/
ReflectHelper.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
/*
* Hibernate, Relational Persistence for Idiomatic Java
*
* License: GNU Lesser General Public License (LGPL), version 2.1 or later.
* See the lgpl.txt file in the root directory or <http://www.gnu.org/licenses/lgpl-2.1.html>.
*/
package org.hibernate.internal.util;
import java.beans.Introspector;
import java.lang.reflect.AccessibleObject;
import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Member;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.TypeVariable;
import java.lang.reflect.WildcardType;
import java.util.Locale;
import java.util.function.Supplier;
import org.hibernate.AssertionFailure;
import org.hibernate.MappingException;
import org.hibernate.PropertyNotFoundException;
import org.hibernate.boot.registry.classloading.spi.ClassLoaderService;
import org.hibernate.boot.registry.classloading.spi.ClassLoadingException;
import org.hibernate.internal.util.collections.ArrayHelper;
import org.hibernate.property.access.internal.PropertyAccessStrategyMixedImpl;
import org.hibernate.property.access.spi.Getter;
import org.hibernate.type.BasicType;
import org.hibernate.type.Type;
import org.hibernate.type.descriptor.java.spi.PrimitiveJavaType;
import jakarta.persistence.Transient;
/**
* Utility class for various reflection operations.
*
* @author Gavin King
* @author Steve Ebersole
* @author Chris Cranford
*/
public final class ReflectHelper {
public static final Class<?>[] NO_PARAM_SIGNATURE = ArrayHelper.EMPTY_CLASS_ARRAY;
public static final Class<?>[] SINGLE_OBJECT_PARAM_SIGNATURE = new Class[] { Object.class };
private static final Method OBJECT_EQUALS;
private static final Method OBJECT_HASHCODE;
private static final Class<?> RECORD_CLASS;
private static final Method GET_RECORD_COMPONENTS;
private static final Method GET_NAME;
private static final Method GET_TYPE;
static {
Method eq;
Method hash;
try {
eq = extractEqualsMethod( Object.class );
hash = extractHashCodeMethod( Object.class );
}
catch ( Exception e ) {
throw new AssertionFailure( "Could not find Object.equals() or Object.hashCode()", e );
}
OBJECT_EQUALS = eq;
OBJECT_HASHCODE = hash;
Class<?> recordClass = null;
Method getRecordComponents = null;
Method getName = null;
Method getType = null;
try {
recordClass = Class.forName( "java.lang.Record" );
getRecordComponents = Class.class.getMethod( "getRecordComponents" );
final Class<?> recordComponentClass = Class.forName( "java.lang.reflect.RecordComponent" );
getName = recordComponentClass.getMethod( "getName" );
getType = recordComponentClass.getMethod( "getType" );
}
catch (Exception e) {
// Ignore
}
RECORD_CLASS = recordClass;
GET_RECORD_COMPONENTS = getRecordComponents;
GET_NAME = getName;
GET_TYPE = getType;
}
/**
* Disallow instantiation of ReflectHelper.
*/
private ReflectHelper() {
}
/**
* Encapsulation of getting hold of a class's {@link Object#equals equals} method.
*
* @param clazz The class from which to extract the equals method.
* @return The equals method reference
* @throws NoSuchMethodException Should indicate an attempt to extract equals method from interface.
*/
public static Method extractEqualsMethod(Class<?> clazz) throws NoSuchMethodException {
return clazz.getMethod( "equals", SINGLE_OBJECT_PARAM_SIGNATURE );
}
/**
* Encapsulation of getting hold of a class's {@link Object#hashCode hashCode} method.
*
* @param clazz The class from which to extract the hashCode method.
* @return The hashCode method reference
* @throws NoSuchMethodException Should indicate an attempt to extract hashCode method from interface.
*/
public static Method extractHashCodeMethod(Class<?> clazz) throws NoSuchMethodException {
return clazz.getMethod( "hashCode", NO_PARAM_SIGNATURE );
}
/**
* Determine if the given class defines an {@link Object#equals} override.
*
* @param clazz The class to check
* @return True if clazz defines an equals override.
*/
public static boolean overridesEquals(Class<?> clazz) {
Method equals;
try {
equals = extractEqualsMethod( clazz );
}
catch ( NoSuchMethodException nsme ) {
return false; //its an interface so we can't really tell anything...
}
return !OBJECT_EQUALS.equals( equals );
}
/**
* Determine if the given class defines a {@link Object#hashCode} override.
*
* @param clazz The class to check
* @return True if clazz defines an hashCode override.
*/
public static boolean overridesHashCode(Class<?> clazz) {
Method hashCode;
try {
hashCode = extractHashCodeMethod( clazz );
}
catch ( NoSuchMethodException nsme ) {
return false; //its an interface so we can't really tell anything...
}
return !OBJECT_HASHCODE.equals( hashCode );
}
/**
* Determine if the given class implements the given interface.
*
* @param clazz The class to check
* @param intf The interface to check it against.
* @return True if the class does implement the interface, false otherwise.
*/
public static boolean implementsInterface(Class<?> clazz, Class<?> intf) {
assert intf.isInterface() : "Interface to check was not an interface";
return intf.isAssignableFrom( clazz );
}
/**
* Perform resolution of a class name.
* <p>
* Here we first check the context classloader, if one, before delegating to
* {@link Class#forName(String, boolean, ClassLoader)} using the caller's classloader
*
* @param name The class name
* @param caller The class from which this call originated (in order to access that class's loader).
* @return The class reference.
* @throws ClassNotFoundException From {@link Class#forName(String, boolean, ClassLoader)}.
*/
public static Class<?> classForName(String name, Class<?> caller) throws ClassNotFoundException {
try {
ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
if ( classLoader != null ) {
return classLoader.loadClass( name );
}
}
catch ( Throwable ignore ) {
}
return Class.forName( name, true, caller.getClassLoader() );
}
/**
* Perform resolution of a class name.
* <p>
* Same as {@link #classForName(String, Class)} except that here we delegate to
* {@link Class#forName(String)} if the context classloader lookup is unsuccessful.
*
* @param name The class name
* @return The class reference.
*
* @throws ClassNotFoundException From {@link Class#forName(String)}.
*
* @deprecated Depending on context, either {@link ClassLoaderService}
* or {@link org.hibernate.boot.spi.ClassLoaderAccess} should be preferred
*/
@Deprecated
public static Class<?> classForName(String name) throws ClassNotFoundException {
try {
ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
if ( classLoader != null ) {
return classLoader.loadClass(name);
}
}
catch ( Throwable ignore ) {
}
return Class.forName( name );
}
/**
* Is this member publicly accessible.
*
* @param clazz The class which defines the member
* @param member The member.
* @return True if the member is publicly accessible, false otherwise.
*/
public static boolean isPublic(Class<?> clazz, Member member) {
return Modifier.isPublic( member.getModifiers() ) && Modifier.isPublic( clazz.getModifiers() );
}
/**
* Attempt to resolve the specified property type through reflection.
*
* @param className The name of the class owning the property.
* @param name The name of the property.
* @param classLoaderService ClassLoader services
*
* @return The type of the property.
*
* @throws MappingException Indicates we were unable to locate the property.
*/
public static Class<?> reflectedPropertyClass(
String className,
String name,
ClassLoaderService classLoaderService) throws MappingException {
try {
Class<?> clazz = classLoaderService.classForName( className );
return getter( clazz, name ).getReturnTypeClass();
}
catch ( ClassLoadingException e ) {
throw new MappingException( "class " + className + " not found while looking for property: " + name, e );
}
}
public static java.lang.reflect.Type reflectedPropertyType(
String className,
String name,
ClassLoaderService classLoaderService) throws MappingException {
try {
Class<?> clazz = classLoaderService.classForName( className );
return getter( clazz, name ).getReturnType();
}
catch ( ClassLoadingException e ) {
throw new MappingException( "class " + className + " not found while looking for property: " + name, e );
}
}
/**
* Attempt to resolve the specified property type through reflection.
*
* @param clazz The class owning the property.
* @param name The name of the property.
* @return The type of the property.
* @throws MappingException Indicates we were unable to locate the property.
*/
public static Class<?> reflectedPropertyClass(Class<?> clazz, String name) throws MappingException {
return getter( clazz, name ).getReturnTypeClass();
}
private static Getter getter(Class<?> clazz, String name) throws MappingException {
return PropertyAccessStrategyMixedImpl.INSTANCE.buildPropertyAccess( clazz, name, true ).getGetter();
}
/**
* Retrieve the default (no arg) constructor from the given class.
*
* @param clazz The class for which to retrieve the default ctor.
* @return The default constructor.
* @throws PropertyNotFoundException Indicates there was not publicly accessible, no-arg constructor (todo : why PropertyNotFoundException???)
*/
public static <T> Constructor<T> getDefaultConstructor(Class<T> clazz) throws PropertyNotFoundException {
if ( isAbstractClass( clazz ) ) {
return null;
}
try {
Constructor<T> constructor = clazz.getDeclaredConstructor( NO_PARAM_SIGNATURE );
ensureAccessibility( constructor );
return constructor;
}
catch ( NoSuchMethodException nme ) {
throw new PropertyNotFoundException(
"Object class [" + clazz.getName() + "] must declare a default (no-argument) constructor"
);
}
}
public static <T> Supplier<T> getDefaultSupplier(Class<T> clazz) {
if ( isAbstractClass( clazz ) ) {
throw new IllegalArgumentException( "Abstract class cannot be instantiated: " + clazz.getName() );
}
try {
final Constructor<T> constructor = clazz.getDeclaredConstructor( NO_PARAM_SIGNATURE );
ensureAccessibility( constructor );
return () -> {
try {
return constructor.newInstance();
}
catch ( InstantiationException|IllegalAccessException|InvocationTargetException e ) {
throw new org.hibernate.InstantiationException( "Constructor threw exception", clazz, e );
}
};
}
catch ( NoSuchMethodException nme ) {
return () -> {
try {
return clazz.newInstance();
}
catch ( InstantiationException|IllegalAccessException e ) {
throw new org.hibernate.InstantiationException( "Default constructor threw exception", clazz, e );
}
};
}
}
/**
* Determine if the given class is declared abstract.
*
* @param clazz The class to check.
* @return True if the class is abstract, false otherwise.
*/
public static boolean isAbstractClass(Class<?> clazz) {
int modifier = clazz.getModifiers();
return Modifier.isAbstract(modifier) || Modifier.isInterface(modifier);
}
/**
* Determine is the given class is declared final.
*
* @param clazz The class to check.
* @return True if the class is final, false otherwise.
*/
public static boolean isFinalClass(Class<?> clazz) {
return Modifier.isFinal( clazz.getModifiers() );
}
/**
* Retrieve a constructor for the given class, with arguments matching
* the specified Hibernate mapping {@linkplain Type types}.
*
* @param clazz The class needing instantiation
* @param types The types representing the required ctor param signature
* @return The matching constructor
* @throws PropertyNotFoundException Indicates we could not locate an appropriate constructor
*
* @deprecated no longer used, since we moved away from the {@link Type} interface
*/
// todo : again with PropertyNotFoundException???
@Deprecated(since = "6", forRemoval = true)
public static Constructor<?> getConstructor(Class<?> clazz, Type[] types) throws PropertyNotFoundException {
final Constructor<?>[] candidates = clazz.getConstructors();
Constructor<?> constructor = null;
int numberOfMatchingConstructors = 0;
for ( final Constructor<?> candidate : candidates ) {
final Class<?>[] params = candidate.getParameterTypes();
if ( params.length == types.length ) {
boolean found = true;
for ( int j = 0; j < params.length; j++ ) {
final boolean ok = types[j] == null || params[j].isAssignableFrom( types[j].getReturnedClass() ) || (
types[j] instanceof BasicType<?> && ( (BasicType<?>) types[j] ).getJavaTypeDescriptor() instanceof PrimitiveJavaType
&& params[j] == ( (PrimitiveJavaType<?>) ( ( (BasicType<?>) types[j] ).getJavaTypeDescriptor() ) ).getPrimitiveClass()
);
if ( !ok ) {
found = false;
break;
}
}
if ( found ) {
numberOfMatchingConstructors ++;
ensureAccessibility( candidate );
constructor = candidate;
}
}
}
if ( numberOfMatchingConstructors == 1 ) {
return constructor;
}
throw new PropertyNotFoundException( "no appropriate constructor in class: " + clazz.getName() );
}
/**
* Retrieve a constructor for the given class, with arguments matching
* the specified Java {@linkplain Class types}, or return {@code null}
* if no such constructor exists.
*
* @param clazz The class needing instantiation
* @param constructorArgs The types representing the required ctor param signature
* @return The matching constructor, or {@code null}
*/
public static <T> Constructor<T> getConstructorOrNull(
Class<T> clazz,
Class<?>... constructorArgs) {
Constructor<T> constructor = null;
try {
constructor = clazz.getDeclaredConstructor( constructorArgs );
try {
ensureAccessibility( constructor );
}
catch ( SecurityException e ) {
constructor = null;
}
}
catch ( NoSuchMethodException ignore ) {
}
return constructor;
}
public static Method getMethod(Class<?> clazz, Method method) {
try {
return clazz.getMethod( method.getName(), method.getParameterTypes() );
}
catch (Exception e) {
return null;
}
}
public static Method getMethod(Class<?> clazz, String methodName, Class<?>... paramTypes) {
try {
return clazz.getMethod( methodName, paramTypes );
}
catch (Exception e) {
return null;
}
}
public static Field findField(Class<?> containerClass, String propertyName) {
if ( containerClass == null ) {
throw new IllegalArgumentException( "Class<?> on which to find field [" + propertyName + "] cannot be null" );
}
else if ( containerClass == Object.class ) {
throw new IllegalArgumentException( "Illegal attempt to locate field [" + propertyName + "] on Object.class" );
}
Field field = locateField( containerClass, propertyName );
if ( field == null ) {
throw new PropertyNotFoundException(
String.format(
Locale.ROOT,
"Could not locate field name [%s] on class [%s]",
propertyName,
containerClass.getName()
)
);
}
ensureAccessibility( field );
return field;
}
public static void ensureAccessibility(AccessibleObject accessibleObject) {
if ( !accessibleObject.isAccessible() ) {
accessibleObject.setAccessible( true );
}
}
private static Field locateField(Class<?> clazz, String propertyName) {
if ( clazz == null || Object.class.equals( clazz ) ) {
return null;
}
try {
Field field = clazz.getDeclaredField( propertyName );
if ( !isStaticField( field ) ) {
return field;
}
return locateField( clazz.getSuperclass(), propertyName );
}
catch ( NoSuchFieldException nsfe ) {
return locateField( clazz.getSuperclass(), propertyName );
}
}
public static boolean isStaticField(Field field) {
return field != null && ( field.getModifiers() & Modifier.STATIC ) == Modifier.STATIC;
}
public static Method findGetterMethod(Class<?> containerClass, String propertyName) {
Class<?> checkClass = containerClass;
Method getter = null;
if ( isRecord( containerClass ) ) {
try {
getter = containerClass.getMethod( propertyName, NO_PARAM_SIGNATURE );
}
catch (NoSuchMethodException e) {
// Ignore
}
}
// check containerClass, and then its super types (if any)
while ( getter == null && checkClass != null ) {
if ( checkClass.equals( Object.class ) ) {
break;
}
getter = getGetterOrNull( checkClass, propertyName );
// if no getter found yet, check all implemented interfaces
if ( getter == null ) {
getter = getGetterOrNull( checkClass.getInterfaces(), propertyName );
}
checkClass = checkClass.getSuperclass();
}
if ( getter == null ) {
throw new PropertyNotFoundException(
String.format(
Locale.ROOT,
"Could not locate getter method for property '%s' of class '%s'",
propertyName,
containerClass.getName()
)
);
}
ensureAccessibility( getter );
return getter;
}
private static Method getGetterOrNull(Class<?>[] interfaces, String propertyName) {
Method getter = null;
for ( int i = 0; getter == null && i < interfaces.length; ++i ) {
final Class<?> anInterface = interfaces[i];
if ( shouldSkipInterfaceCheck( anInterface ) ) {
continue;
}
getter = getGetterOrNull( anInterface, propertyName );
if ( getter == null ) {
// if no getter found yet, check all implemented interfaces of interface
getter = getGetterOrNull( anInterface.getInterfaces(), propertyName );
}
}
return getter;
}
/**
* Find the method that can be used as the getter for this property.
*
* @param containerClass The Class<?> which contains the property
* @param propertyName The name of the property
*
* @return The getter method, or {@code null} if there is none.
*
* @throws MappingException If the {@code containerClass} has both a get- and an is- form.
*/
public static Method getGetterOrNull(Class<?> containerClass, String propertyName) {
if ( isRecord( containerClass ) ) {
try {
return containerClass.getMethod( propertyName, NO_PARAM_SIGNATURE );
}
catch (NoSuchMethodException e) {
// Ignore
}
}
for ( Method method : containerClass.getDeclaredMethods() ) {
// if the method has parameters, skip it
if ( method.getParameterCount() != 0 ) {
continue;
}
// if the method is a "bridge", skip it
if ( method.isBridge() ) {
continue;
}
if ( method.getAnnotation( Transient.class ) != null ) {
continue;
}
if ( Modifier.isStatic( method.getModifiers() ) ) {
continue;
}
final String methodName = method.getName();
// try "get"
if ( methodName.startsWith( "get" ) ) {
final String stemName = methodName.substring( 3 );
final String decapitalizedStemName = Introspector.decapitalize( stemName );
if ( stemName.equals( propertyName ) || decapitalizedStemName.equals( propertyName ) ) {
verifyNoIsVariantExists( containerClass, propertyName, method, stemName );
return method;
}
}
// if not "get", then try "is"
if ( methodName.startsWith( "is" ) ) {
final String stemName = methodName.substring( 2 );
String decapitalizedStemName = Introspector.decapitalize( stemName );
if ( stemName.equals( propertyName ) || decapitalizedStemName.equals( propertyName ) ) {
// not sure that this can ever really happen given the handling of "get" above.
// but be safe
verifyNoGetVariantExists( containerClass, propertyName, method, stemName );
return method;
}
}
}
return null;
}
public static void verifyNoIsVariantExists(
Class<?> containerClass,
String propertyName,
Method getMethod,
String stemName) {
// verify that the Class<?> does not also define a method with the same stem name with 'is'
try {
final Method isMethod = containerClass.getDeclaredMethod( "is" + stemName );
if ( !Modifier.isStatic( isMethod.getModifiers() ) && isMethod.getAnnotation( Transient.class ) == null ) {
// No such method should throw the caught exception. So if we get here, there was
// such a method.
checkGetAndIsVariants( containerClass, propertyName, getMethod, isMethod );
}
}
catch (NoSuchMethodException ignore) {
}
}
public static void checkGetAndIsVariants(
Class<?> containerClass,
String propertyName,
Method getMethod,
Method isMethod) {
// Check the return types. If they are the same, its ok. If they are different
// we are in a situation where we could not reasonably know which to use.
if ( !isMethod.getReturnType().equals( getMethod.getReturnType() ) ) {
throw new MappingException(
String.format(
Locale.ROOT,
"Class<?> '%s' declares both 'get' [%s] and 'is' [%s] variants of getter for property '%s'",
containerClass.getName(),
getMethod,
isMethod,
propertyName
)
);
}
}
public static void verifyNoGetVariantExists(
Class<?> containerClass,
String propertyName,
Method isMethod,
String stemName) {
// verify that the Class<?> does not also define a method with the same stem name with 'is'
try {
final Method getMethod = containerClass.getDeclaredMethod( "get" + stemName );
// No such method should throw the caught exception. So if we get here, there was
// such a method.
if ( !Modifier.isStatic( getMethod.getModifiers() ) && getMethod.getAnnotation( Transient.class ) == null ) {
checkGetAndIsVariants( containerClass, propertyName, getMethod, isMethod );
}
}
catch (NoSuchMethodException ignore) {
}
}
public static Method getterMethodOrNull(Class<?> containerJavaType, String propertyName) {
try {
return findGetterMethod( containerJavaType, propertyName );
}
catch (PropertyNotFoundException e) {
return null;
}
}
public static Method setterMethodOrNull(final Class<?> containerClass, final String propertyName, final Class<?> propertyType) {
//Computes the most likely setter name - there might be fallback choices to try, but we try this one first
//to try not overwhelming the system with swallowed exceptions.
final String likelyMethodName = likelySetterMethodNameForProperty( propertyName );
//First let's test the most obvious solution: a public method having exactly the expected name and type;
//this has the benefit of including parent types and interfaces w/o extensively bothering the reflection api
//which is very allocation intensive - this is noticeable on bootstrap costs on large models.
try {
final Method setter = containerClass.getMethod( likelyMethodName, propertyType );
ensureAccessibility( setter );
return setter;
}
catch ( NoSuchMethodException e ) {
//No luck: we'll need to run the more expensive but thorough process
}
Class<?> checkClass = containerClass;
Method setter = null;
// check containerClass, and then its super types (if any)
while ( setter == null && checkClass != null ) {
if ( checkClass.equals( Object.class ) ) {
break;
}
setter = setterOrNull( checkClass, propertyName, propertyType, likelyMethodName );
// if no setter found yet, check all implemented interfaces
if ( setter == null ) {
setter = setterOrNull( checkClass.getInterfaces(), propertyName, propertyType, likelyMethodName );
}
else {
ensureAccessibility( setter );
}
checkClass = checkClass.getSuperclass();
}
return setter; // might be null
}
public static Method setterMethodOrNullBySetterName(final Class<?> containerClass, final String setterName, final Class<?> propertyType) {
Class<?> checkClass = containerClass;
Method setter = null;
// check containerClass, and then its super types (if any)
while ( setter == null && checkClass != null ) {
if ( checkClass.equals( Object.class ) ) {
break;
}
setter = setterOrNullBySetterName( checkClass, setterName, propertyType );
// if no setter found yet, check all implemented interfaces
if ( setter == null ) {
setter = setterOrNullBySetterName( checkClass.getInterfaces(), setterName, propertyType );
}
else {
ensureAccessibility( setter );
}
checkClass = checkClass.getSuperclass();
}
return setter; // might be null
}
private static Method setterOrNullBySetterName(Class<?>[] interfaces, String setterName, Class<?> propertyType) {
Method setter = null;
for ( int i = 0; setter == null && i < interfaces.length; ++i ) {
final Class<?> anInterface = interfaces[i];
if ( shouldSkipInterfaceCheck( anInterface ) ) {
continue;
}
setter = setterOrNullBySetterName( anInterface, setterName, propertyType );
if ( setter == null ) {
// if no setter found yet, check all implemented interfaces of interface
setter = setterOrNullBySetterName( anInterface.getInterfaces(), setterName, propertyType );
}
}
return setter;
}
private static boolean shouldSkipInterfaceCheck(final Class anInterface) {
final String interfaceName = anInterface.getName();
//Skip checking any interface that we've added ourself via bytecode enhancement:
//there's many of those and it's pointless to look there.
if ( interfaceName.startsWith( "org.hibernate.engine." ) ) {
return true;
}
//Also skip jakarta.persistence prefixed interfaces, as otherwise we'll be scanning
//among mapping annotations as well:
if ( interfaceName.startsWith( "jakarta.persistence." ) ) {
return true;
}
return false;
}
private static Method setterOrNullBySetterName(Class<?> theClass, String setterName, Class<?> propertyType) {
Method potentialSetter = null;
for ( Method method : theClass.getDeclaredMethods() ) {
final String methodName = method.getName();
if ( method.getParameterCount() == 1 && methodName.equals( setterName ) ) {
potentialSetter = method;
if ( propertyType == null || method.getParameterTypes()[0].equals( propertyType ) ) {
break;
}
}
}
return potentialSetter;
}
public static Method findSetterMethod(final Class<?> containerClass, final String propertyName, final Class<?> propertyType) {
final Method setter = setterMethodOrNull( containerClass, propertyName, propertyType );
if ( setter == null ) {
throw new PropertyNotFoundException(
String.format(
Locale.ROOT,
"Could not locate setter method for property '%s' of class '%s'",
propertyName,
containerClass.getName()
)
);
}
return setter;
}
private static Method setterOrNull(Class<?>[] interfaces, String propertyName, Class<?> propertyType, String likelyMethodName) {
Method setter = null;
for ( int i = 0; setter == null && i < interfaces.length; ++i ) {
final Class<?> anInterface = interfaces[i];
if ( shouldSkipInterfaceCheck( anInterface ) ) {
continue;
}
setter = setterOrNull( anInterface, propertyName, propertyType, likelyMethodName );
if ( setter == null ) {
// if no setter found yet, check all implemented interfaces of interface
setter = setterOrNull( anInterface.getInterfaces(), propertyName, propertyType, likelyMethodName );
}
}
return setter;
}
private static Method setterOrNull(Class<?> theClass, String propertyName, Class propertyType, String likelyMethodName) {
try {
return theClass.getDeclaredMethod( likelyMethodName, propertyType );
}
catch ( NoSuchMethodException e ) {
//Ignore, so we try the old method for best compatibility (even though it's less efficient) next:
}
Method potentialSetter = null;
for ( Method method : theClass.getDeclaredMethods() ) {
final String methodName = method.getName();
if ( method.getParameterCount() == 1 && methodName.startsWith( "set" ) ) {
final String testOldMethod = methodName.substring( 3 );
final String testStdMethod = Introspector.decapitalize( testOldMethod );
if ( testStdMethod.equals( propertyName ) || testOldMethod.equals( propertyName ) ) {
potentialSetter = method;
if ( propertyType == null || method.getParameterTypes()[0].equals( propertyType ) ) {
break;
}
}
}
}
return potentialSetter;
}
private static String likelySetterMethodNameForProperty(final String propertyName) {
final char firstCharacter = propertyName.charAt( 0 );
if ( Character.isLowerCase( firstCharacter ) ) {
return "set" + Character.toUpperCase( firstCharacter ) + propertyName.substring( 1 );
}
else {
return "set" + propertyName;
}
}
/**
* Similar to {@link #getterMethodOrNull}, except that here we are just looking for the
* corresponding getter for a field (defined as field access) if one exists.
* <p>
* We do not look at supers, although conceivably the super could declare the method
* as an abstract - but again, that is such an edge case...
*/
public static Method findGetterMethodForFieldAccess(Field field, String propertyName) {
for ( Method method : field.getDeclaringClass().getDeclaredMethods() ) {
// if the method has parameters, skip it
if ( method.getParameterCount() != 0 ) {
continue;
}
if ( Modifier.isStatic( method.getModifiers() ) ) {
continue;
}
if ( ! method.getReturnType().isAssignableFrom( field.getType() ) ) {
continue;
}
final String methodName = method.getName();
// try "get"
if ( methodName.startsWith( "get" ) ) {
final String stemName = methodName.substring( 3 );
final String decapitalizedStemName = Introspector.decapitalize( stemName );
if ( stemName.equals( propertyName ) || decapitalizedStemName.equals( propertyName ) ) {
return method;
}
}
// if not "get", then try "is"
if ( methodName.startsWith( "is" ) ) {
final String stemName = methodName.substring( 2 );
String decapitalizedStemName = Introspector.decapitalize( stemName );
if ( stemName.equals( propertyName ) || decapitalizedStemName.equals( propertyName ) ) {
return method;
}
}
}
if ( isRecord( field.getDeclaringClass() ) ) {
try {
return field.getDeclaringClass().getMethod( field.getName(), NO_PARAM_SIGNATURE );
}
catch (NoSuchMethodException e) {
// Ignore
}
}
return null;
}
public static boolean isRecord(Class<?> declaringClass) {
return RECORD_CLASS != null && RECORD_CLASS.isAssignableFrom( declaringClass );
}
public static Class<?>[] getRecordComponentTypes(Class<?> javaType) {
try {
final Object[] recordComponents = (Object[]) GET_RECORD_COMPONENTS.invoke( javaType );
final Class<?>[] componentTypes = new Class[recordComponents.length];
for (int i = 0; i < recordComponents.length; i++ ) {
componentTypes[i] = (Class<?>) GET_TYPE.invoke( recordComponents[i] );
}
return componentTypes;
}
catch (Exception e) {
throw new IllegalArgumentException(
"Could not determine the record components for: " + javaType.getName(),
e
);
}
}
public static String[] getRecordComponentNames(Class<?> javaType) {
try {
final Object[] recordComponents = (Object[]) GET_RECORD_COMPONENTS.invoke( javaType );
final String[] componentNames = new String[recordComponents.length];
for (int i = 0; i < recordComponents.length; i++ ) {
componentNames[i] = (String) GET_NAME.invoke( recordComponents[i] );
}
return componentNames;
}
catch (Exception e) {
throw new IllegalArgumentException(
"Could not determine the record components for: " + javaType.getName(),
e
);
}
}
public static <T> Class<T> getClass(java.lang.reflect.Type type) {
if ( type == null ) {
return null;
}
else if ( type instanceof Class<?> ) {
return (Class<T>) type;
}
else if ( type instanceof ParameterizedType ) {
return (Class<T>) ( (ParameterizedType) type ).getRawType();
}
else if ( type instanceof TypeVariable ) {
return getClass( ( (TypeVariable<?>) type ).getBounds()[0] );
}
else if ( type instanceof WildcardType ) {
return getClass( ( (WildcardType) type ).getUpperBounds()[0] );
}
throw new UnsupportedOperationException( "Can't get java type class from type: " + type );
}
public static Class<?> getPropertyType(Member member) {
if (member instanceof Field) {
return ( (Field) member ).getType();
}
else if (member instanceof Method) {
return ( (Method) member ).getReturnType();
}
else {
throw new AssertionFailure("member should have been a method or field");
}
}
public static boolean isClass(Class<?> resultClass) {
return !resultClass.isArray()
&& !resultClass.isPrimitive()