-
Notifications
You must be signed in to change notification settings - Fork 348
/
ReflectionHelper.java
1581 lines (1459 loc) · 62.6 KB
/
ReflectionHelper.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
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 (c) 2010, 2022 Oracle and/or its affiliates. All rights reserved.
*
* This program and the accompanying materials are made available under the
* terms of the Eclipse Public License v. 2.0, which is available at
* http://www.eclipse.org/legal/epl-2.0.
*
* This Source Code may also be made available under the following Secondary
* Licenses when the conditions for such availability set forth in the
* Eclipse Public License v. 2.0 are satisfied: GNU General Public License,
* version 2 with the GNU Classpath Exception, which is available at
* https://www.gnu.org/software/classpath/license.html.
*
* SPDX-License-Identifier: EPL-2.0 OR GPL-2.0 WITH Classpath-exception-2.0
*/
package org.glassfish.jersey.internal.util;
import java.io.IOException;
import java.io.InputStream;
import java.lang.annotation.Annotation;
import java.lang.reflect.AccessibleObject;
import java.lang.reflect.AnnotatedElement;
import java.lang.reflect.Array;
import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.GenericArrayType;
import java.lang.reflect.Member;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.lang.reflect.TypeVariable;
import java.lang.reflect.WildcardType;
import java.net.URL;
import java.security.AccessController;
import java.security.PrivilegedAction;
import java.security.PrivilegedExceptionAction;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.IdentityHashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.function.Function;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.util.stream.Collectors;
import javax.ws.rs.core.GenericEntity;
import javax.ws.rs.core.GenericType;
import org.glassfish.jersey.internal.LocalizationMessages;
import org.glassfish.jersey.internal.OsgiRegistry;
import org.glassfish.jersey.internal.util.collection.ClassTypePair;
import org.glassfish.jersey.internal.util.collection.LazyValue;
import org.glassfish.jersey.internal.util.collection.Value;
import org.glassfish.jersey.internal.util.collection.Values;
import org.osgi.framework.Bundle;
import org.osgi.framework.FrameworkUtil;
/**
* Utility methods for Java reflection.
*
* @author Paul Sandoz
* @author Jakub Podlesak
*/
public final class ReflectionHelper {
private static final Logger LOGGER = Logger.getLogger(ReflectionHelper.class.getName());
private static final PrivilegedAction<?> NoOpPrivilegedACTION = new PrivilegedAction<Object>() {
@Override
public Object run() {
return null;
}
};
/**
* Prevents instantiation.
*/
private ReflectionHelper() {
throw new AssertionError("No instances allowed.");
}
/**
* Get the declaring class of an accessible object.
* <p>
* Supported are {@link Method}, {@link Field} and {@link Constructor} accessible object types.
* </p>
*
* @param ao an accessible object.
* @return the declaring class of an accessible object.
* @throws IllegalArgumentException in case the type of the accessible object
* is not supported.
*/
public static Class<?> getDeclaringClass(final AccessibleObject ao) {
if (ao instanceof Member && (ao instanceof Field || ao instanceof Method || ao instanceof Constructor)) {
return ((Member) ao).getDeclaringClass();
} else {
throw new IllegalArgumentException("Unsupported accessible object type: " + ao.getClass().getName());
}
}
/**
* Create a string representation of an object.
* <p>
* Returns a string consisting of the name of the class of which the
* object is an instance, the at-sign character {@code '@'}, and
* the unsigned hexadecimal representation of the hash code of the
* object. In other words, this method returns a string equal to the
* value of:
* </p>
* <pre>
* o.getClass().getName() + '@' + Integer.toHexString(o.hashCode())
* </pre>
*
* @param o the object.
* @return the string representation of the object.
*/
public static String objectToString(final Object o) {
if (o == null) {
return "null";
}
return o.getClass().getName() + '@' + Integer.toHexString(o.hashCode());
}
/**
* Create a string representation of a method and an instance whose
* class implements the method.
* <p>
* Returns a string consisting of the name of the class of which the object
* is an instance, the at-sign character {@code '@'},
* the unsigned hexadecimal representation of the hash code of the
* object, the character {@code '.'}, the name of the method,
* the character {@code '('}, the list of method parameters, and
* the character {@code ')'}. In other words, those method returns a
* string equal to the value of:
* </p>
* <pre>
* o.getClass().getName() + '@' + Integer.toHexString(o.hashCode()) +
* '.' + m.getName() + '(' + <parameters> + ')'.</pre>
*
* @param o the object whose class implements {@code m}.
* @param m the method.
* @return the string representation of the method and instance.
*/
public static String methodInstanceToString(final Object o, final Method m) {
final StringBuilder sb = new StringBuilder();
sb.append(o.getClass().getName())
.append('@').append(Integer.toHexString(o.hashCode()))
.append('.').append(m.getName()).append('(');
final Class[] params = m.getParameterTypes();
for (int i = 0; i < params.length; i++) {
sb.append(getTypeName(params[i]));
if (i < (params.length - 1)) {
sb.append(",");
}
}
sb.append(')');
return sb.toString();
}
/**
* Get the Java type or array name.
* <p>
* If the class is representing an array, the {@code "[]"} suffix will be added
* to the name of the type for each dimension of an array.
* </p>
*
* @param type Java type (can represent an array).
* @return Java type or array name.
*/
private static String getTypeName(final Class<?> type) {
if (type.isArray()) {
Class<?> cl = type;
int dimensions = 0;
while (cl.isArray()) {
dimensions++;
cl = cl.getComponentType();
}
final StringBuilder sb = new StringBuilder();
sb.append(cl.getName());
for (int i = 0; i < dimensions; i++) {
sb.append("[]");
}
return sb.toString();
}
return type.getName();
}
/**
* Get privileged action to obtain Class from given class name.
* <p>
* If run using security manager, the returned privileged action
* must be invoked within a doPrivileged block.
* The context class loader will be utilized if accessible and non-null.
* Otherwise the defining class loader of this class will
* be utilized.
* </p>
*
* @param <T> class type.
* @param name class name.
* @return privileged action to obtain desired Class.
* The action could return {@code null} if the class cannot be found.
* @see AccessController#doPrivileged(java.security.PrivilegedAction)
*/
public static <T> PrivilegedAction<Class<T>> classForNamePA(final String name) {
return classForNamePA(name, getContextClassLoader());
}
/**
* Get privileged action to obtain Class from given class name.
* If run using security manager, the returned privileged action
* must be invoked within a doPrivileged block.
*
* @param <T> class type.
* @param name class name.
* @param cl class loader to use, if {@code null} then the defining class loader
* of this class will be utilized.
* @return privileged action to obtain desired Class. The action could return {@code null} if the class cannot be found.
* @see AccessController#doPrivileged(java.security.PrivilegedAction)
*/
@SuppressWarnings("unchecked")
public static <T> PrivilegedAction<Class<T>> classForNamePA(final String name, final ClassLoader cl) {
return new PrivilegedAction<Class<T>>() {
@Override
public Class<T> run() {
if (cl != null) {
try {
return (Class<T>) Class.forName(name, false, cl);
} catch (final ClassNotFoundException ex) {
if (LOGGER.isLoggable(Level.FINER)) {
LOGGER.log(Level.FINER,
"Unable to load class " + name + " using the supplied class loader "
+ cl.getClass().getName() + ".", ex);
}
}
}
try {
return (Class<T>) Class.forName(name);
} catch (final ClassNotFoundException ex) {
if (LOGGER.isLoggable(Level.FINER)) {
LOGGER.log(Level.FINER, "Unable to load class " + name + " using the current class loader.", ex);
}
}
return null;
}
};
}
/**
* Get privileged action to obtain class loader for given class.
* If run using security manager, the returned privileged action
* must be invoked within a doPrivileged block.
*
* @param clazz class for which to get class loader.
* @return privileged action to obtain class loader for the {@code clazz} class.
* @see AccessController#doPrivileged(java.security.PrivilegedAction)
*/
public static PrivilegedAction<ClassLoader> getClassLoaderPA(final Class<?> clazz) {
return new PrivilegedAction<ClassLoader>() {
@Override
public ClassLoader run() {
return clazz.getClassLoader();
}
};
}
/**
* Get privileged action to obtain fields declared on given class.
* If run using security manager, the returned privileged action
* must be invoked within a doPrivileged block.
*
* @param clazz class for which to get the declared fields.
* @return privileged action to obtain fields declared on the {@code clazz} class.
* @see AccessController#doPrivileged(java.security.PrivilegedAction)
*/
public static PrivilegedAction<Field[]> getDeclaredFieldsPA(final Class<?> clazz) {
return new PrivilegedAction<Field[]>() {
@Override
public Field[] run() {
return clazz.getDeclaredFields();
}
};
}
/**
* Get privileged action to obtain fields on given class, recursively through inheritance hierarchy.
* If run using security manager, the returned privileged action
* must be invoked within a doPrivileged block.
*
* @param clazz class for which to get fields.
* @return privileged action to obtain fields declared on the {@code clazz} class.
* @see AccessController#doPrivileged(java.security.PrivilegedAction)
*/
public static PrivilegedAction<Field[]> getAllFieldsPA(final Class<?> clazz) {
return new PrivilegedAction<Field[]>() {
@Override
public Field[] run() {
final List<Field> fields = new ArrayList<Field>();
recurse(clazz, fields);
return fields.toArray(new Field[fields.size()]);
}
private void recurse(final Class<?> clazz, final List<Field> fields) {
fields.addAll(Arrays.asList(clazz.getDeclaredFields()));
if (clazz.getSuperclass() != null) {
recurse(clazz.getSuperclass(), fields);
}
}
};
}
/**
* Get privileged action to obtain methods declared on given class.
* If run using security manager, the returned privileged action
* must be invoked within a doPrivileged block.
*
* @param clazz class for which to get the declared methods.
* @return privileged action to obtain methods declared on the {@code clazz} class.
* @see AccessController#doPrivileged(java.security.PrivilegedAction)
*/
public static PrivilegedAction<Collection<? extends Method>> getDeclaredMethodsPA(final Class<?> clazz) {
return new PrivilegedAction<Collection<? extends Method>>() {
@Override
public Collection<? extends Method> run() {
return Arrays.asList(clazz.getDeclaredMethods());
}
};
}
/**
* Get privileged exception action to obtain Class from given class name.
* If run using security manager, the returned privileged exception action
* must be invoked within a doPrivileged block.
* <p/>
* The actual context class loader will be utilized if accessible and non-null.
* Otherwise the defining class loader of the calling class will be utilized.
*
* @param <T> class type.
* @param name class name.
* @return privileged exception action to obtain the Class.
* The action could throw {@link ClassNotFoundException} or return {@code null} if the class cannot be found.
* @throws ClassNotFoundException in case the class cannot be loaded with the context class loader.
* @see AccessController#doPrivileged(java.security.PrivilegedExceptionAction)
*/
public static <T> PrivilegedExceptionAction<Class<T>> classForNameWithExceptionPEA(final String name)
throws ClassNotFoundException {
return classForNameWithExceptionPEA(name, getContextClassLoader());
}
/**
* Get privileged exception action to obtain Class from given class name.
* If run using security manager, the returned privileged exception action
* must be invoked within a doPrivileged block.
*
* @param <T> class type.
* @param name class name.
* @param cl class loader to use, if {@code null} then the defining class loader
* of the calling class will be utilized.
* @return privileged exception action to obtain the Class. If the class cannot be found, the action returns {@code null},
* or throws {@link ClassNotFoundException} in case the class loader has been specified.
* @throws ClassNotFoundException in case the class cannot be loaded with the specified class loader.
* @see AccessController#doPrivileged(java.security.PrivilegedExceptionAction)
*/
@SuppressWarnings("unchecked")
public static <T> PrivilegedExceptionAction<Class<T>> classForNameWithExceptionPEA(final String name, final ClassLoader cl)
throws ClassNotFoundException {
return new PrivilegedExceptionAction<Class<T>>() {
@Override
public Class<T> run() throws ClassNotFoundException {
if (cl != null) {
try {
return (Class<T>) Class.forName(name, false, cl);
} catch (final ClassNotFoundException ex) {
// ignored on purpose
}
}
return (Class<T>) Class.forName(name);
}
};
}
/**
* Get privileged action to obtain context class loader.
* If run using security manager, the returned privileged action
* must be invoked within a doPrivileged block.
*
* @return privileged action to obtain the actual context class loader. The action could return {@code null}
* if the context class loader has not been set.
* @see AccessController#doPrivileged(java.security.PrivilegedAction)
*/
public static PrivilegedAction<ClassLoader> getContextClassLoaderPA() {
return new PrivilegedAction<ClassLoader>() {
@Override
public ClassLoader run() {
return Thread.currentThread().getContextClassLoader();
}
};
}
/**
* Get the context class loader.
*
* @return the context class loader, otherwise {@code null} if not set.
*/
private static ClassLoader getContextClassLoader() {
return AccessController.doPrivileged(getContextClassLoaderPA());
}
/**
* Get privileged action to set the actual context class loader.
* If run using security manager, the returned privileged action
* must be invoked within a doPrivileged block.
*
* @param classLoader context class loader to be set.
* @return privileged action to set context class loader.
* @see AccessController#doPrivileged(java.security.PrivilegedAction)
*/
public static PrivilegedAction setContextClassLoaderPA(final ClassLoader classLoader) {
return new PrivilegedAction() {
@Override
public Object run() {
Thread.currentThread().setContextClassLoader(classLoader);
return null;
}
};
}
/**
* Get privileged action to set a method to be accessible.
* If run using security manager, the returned privileged action
* must be invoked within a doPrivileged block.
*
* @param m method to be set as accessible.
* @return privileged action to set the method to be accessible.
* @see AccessController#doPrivileged(java.security.PrivilegedAction)
*/
public static PrivilegedAction setAccessibleMethodPA(final Method m) {
if (Modifier.isPublic(m.getModifiers())) {
return NoOpPrivilegedACTION;
}
return new PrivilegedAction<Object>() {
@Override
public Object run() {
if (!m.isAccessible()) {
m.setAccessible(true);
}
return m;
}
};
}
/**
* Get the list of classes that represent the type arguments of a
* {@link ParameterizedType parameterized} input type.
* <p/>
* For any given argument in the returned list, following rules apply:
* <ul>
* <li>If a type argument is a class then the class is returned.</li>
* <li>If the type argument is a generic array type and the generic component
* type is a class then class of the array is returned.</li>
* <li>If the type argument is a parameterized type and it's raw type is a
* class then that class is returned.</li>
* </ul>
* If the {@code type} is not an instance of ParameterizedType an empty
* list is returned.
*
* @param type parameterized type.
* @return the list of classed representing the actual type arguments. May be empty,
* but may never be {@code null}.
* @throws IllegalArgumentException if any of the generic type arguments is
* not a class, or a generic array type, or the generic component type
* of the generic array type is not class, or not a parameterized type
* with a raw type that is not a class.
*/
public static List<Class<?>> getGenericTypeArgumentClasses(final Type type) throws IllegalArgumentException {
final Type[] types = getTypeArguments(type);
if (types == null) {
return Collections.emptyList();
}
return Arrays.stream(types)
.map((Function<Type, Class<?>>) ReflectionHelper::erasure)
.collect(Collectors.toList());
}
/**
* Get the list of class-type pairs that represent the type arguments of a
* {@link ParameterizedType parameterized} input type.
* <p/>
* For any given {@link ClassTypePair#rawClass() class} part of each pair
* in the returned list, following rules apply:
* <ul>
* <li>If a type argument is a class then the class is returned as raw class.</li>
* <li>If the type argument is a generic array type and the generic component
* type is a class then class of the array is returned as raw class.</li>
* <li>If the type argument is a parameterized type and it's raw type is a
* class then that class is returned as raw class.</li>
* </ul>
* If the {@code type} is not an instance of ParameterizedType an empty
* list is returned.
*
* @param type parameterized type.
* @return the list of class-type pairs representing the actual type arguments. May be empty, but may never be {@code null}.
* @throws IllegalArgumentException if any of the generic type arguments is
* not a class, or a generic array type, or the generic component type
* of the generic array type is not class, or not a parameterized type
* with a raw type that is not a class.
*/
public static List<ClassTypePair> getTypeArgumentAndClass(final Type type) throws IllegalArgumentException {
final Type[] types = getTypeArguments(type);
if (types == null) {
return Collections.emptyList();
}
return Arrays.stream(types)
.map(type1 -> ClassTypePair.of(erasure(type1), type1))
.collect(Collectors.toList());
}
/**
* Check if the given type is a primitive type.
*
* @param type type to be checked.
* @return {@code true} in case the type represents a primitive type, otherwise returns {@code false}.
*/
public static boolean isPrimitive(final Type type) {
if (type instanceof Class) {
final Class c = (Class) type;
return c.isPrimitive();
}
return false;
}
/**
* Get the type arguments for a parameterized type.
* <p/>
* In case the type is not a {@link ParameterizedType parameterized type},
* the method returns {@code null}.
*
* @param type parameterized type.
* @return type arguments for a parameterized type, or {@code null} in case the input type is not a parameterized type.
*/
public static Type[] getTypeArguments(final Type type) {
if (!(type instanceof ParameterizedType)) {
return null;
}
return ((ParameterizedType) type).getActualTypeArguments();
}
/**
* Get a type argument at particular index for a parameterized type.
* <p/>
* In case the type is not a {@link ParameterizedType parameterized type},
* the method returns {@code null}.
*
* @param type parameterized type.
* @param index type parameter index.
* @return type argument for a parameterized type at a given index, or {@code null} in case the input type is not
* a parameterized type.
*/
public static Type getTypeArgument(final Type type, final int index) {
if (type instanceof ParameterizedType) {
final ParameterizedType p = (ParameterizedType) type;
return fix(p.getActualTypeArguments()[index]);
}
return null;
}
/**
* JDK 5.0 has a bug of creating {@link GenericArrayType} where it shouldn't.
* fix that manually to work around the problem.
* <p/>
* See bug 6202725.
*/
private static Type fix(final Type t) {
if (!(t instanceof GenericArrayType)) {
return t;
}
final GenericArrayType gat = (GenericArrayType) t;
if (gat.getGenericComponentType() instanceof Class) {
final Class c = (Class) gat.getGenericComponentType();
return Array.newInstance(c, 0).getClass();
}
return t;
}
/**
* Implements the logic for {@link #erasure(Type)}.
*/
private static final TypeVisitor<Class> eraser = new TypeVisitor<Class>() {
@Override
protected Class onClass(final Class clazz) {
return clazz;
}
@Override
protected Class onParameterizedType(final ParameterizedType type) {
return visit(type.getRawType());
}
@Override
protected Class onGenericArray(final GenericArrayType type) {
return Array.newInstance(visit(type.getGenericComponentType()), 0).getClass();
}
@Override
protected Class onVariable(final TypeVariable type) {
return visit(type.getBounds()[0]);
}
@Override
protected Class onWildcard(final WildcardType type) {
return visit(type.getUpperBounds()[0]);
}
@Override
protected RuntimeException createError(final Type type) {
return new IllegalArgumentException(LocalizationMessages.TYPE_TO_CLASS_CONVERSION_NOT_SUPPORTED(type));
}
};
/**
* Get the {@link Class} representation of the given type.
* <p/>
* This corresponds to the notion of the erasure in JSR-14.
*
* @param type type to provide the erasure for.
* @return the given type's erasure.
*/
@SuppressWarnings("unchecked")
public static <T> Class<T> erasure(final Type type) {
return eraser.visit(type);
}
/**
* Check if {@code subType} is a sub-type of {@code superType}.
*
* @param subType sub-type type.
* @param superType super-type type.
* @return {@code true} in case the {@code subType} is a sub-type of {@code superType},
* {@code false} otherwise.
*/
public static boolean isSubClassOf(final Type subType, final Type superType) {
return erasure(superType).isAssignableFrom(erasure(subType));
}
/**
* Checks if the type is an array type.
*
* @param type type to check.
* @return {@code true} in case the type is an array type, {@code false} otherwise.
*/
public static boolean isArray(final Type type) {
if (type instanceof Class) {
final Class c = (Class) type;
return c.isArray();
}
return type instanceof GenericArrayType;
}
/**
* Checks if the type is an array of a given component type.
*
* @param type type to check.
* @param componentType array component type.
* @return {@code true} in case the type is an array type of a given component type,
* {@code false} otherwise.
*/
public static boolean isArrayOfType(final Type type, final Class<?> componentType) {
if (type instanceof Class) {
final Class c = (Class) type;
return c.isArray() && c != byte[].class;
}
if (type instanceof GenericArrayType) {
final Type arrayComponentType = ((GenericArrayType) type).getGenericComponentType();
return arrayComponentType == componentType;
}
return false;
}
/**
* Gets the component type of the array.
*
* @param type must be an array.
* @return array component type.
* @throws IllegalArgumentException in case the type is not an array type.
*/
public static Type getArrayComponentType(final Type type) {
if (type instanceof Class) {
final Class c = (Class) type;
return c.getComponentType();
}
if (type instanceof GenericArrayType) {
return ((GenericArrayType) type).getGenericComponentType();
}
throw new IllegalArgumentException();
}
/**
* Get Array class of component type.
*
* @param c the component class of the array
* @return the array class.
*/
public static Class<?> getArrayForComponentType(final Class<?> c) {
try {
final Object o = Array.newInstance(c, 0);
return o.getClass();
} catch (final Exception e) {
throw new IllegalArgumentException(e);
}
}
/**
* Get privileged action to obtain the static valueOf(String ) method.
* If run using security manager, the returned privileged action
* must be invoked within a doPrivileged block.
*
* @param clazz class to obtain the method.
* @return privileged action to get the method.
* The action could return {@code null} if the method is not present.
* @see AccessController#doPrivileged(java.security.PrivilegedAction)
*/
@SuppressWarnings("unchecked")
public static PrivilegedAction<Method> getValueOfStringMethodPA(final Class<?> clazz) {
return getStringToObjectMethodPA(clazz, "valueOf");
}
/**
* Get privileged action to get the static fromString(String ) method.
* If run using security manager, the returned privileged action
* must be invoked within a doPrivileged block.
*
* @param clazz class for which to get the method.
* @return privileged action to obtain the method.
* The action could return {@code null} if the method is not present.
* @see AccessController#doPrivileged(java.security.PrivilegedAction)
*/
@SuppressWarnings("unchecked")
public static PrivilegedAction<Method> getFromStringStringMethodPA(final Class<?> clazz) {
return getStringToObjectMethodPA(clazz, "fromString");
}
/**
* Get privileged action to get the static method of given name. If run using security manager, the returned privileged
* action
* must be invoked within a doPrivileged block.
*
* @param clazz class for which to get the method.
* @param methodName name of the method to be obtained.
* @return privileged action to obtain the method.
* The action could return {@code null} if the method is not present.
* @see AccessController#doPrivileged(java.security.PrivilegedAction)
*/
private static PrivilegedAction<Method> getStringToObjectMethodPA(final Class<?> clazz, final String methodName) {
return new PrivilegedAction<Method>() {
@Override
public Method run() {
try {
final Method method = clazz.getDeclaredMethod(methodName, String.class);
if (Modifier.isStatic(method.getModifiers()) && method.getReturnType() == clazz) {
return method;
}
return null;
} catch (final NoSuchMethodException nsme) {
return null;
}
}
};
}
/**
* Get privileged action to obtain constructor that has a single parameter of String.
* If run using security manager, the returned privileged action
* must be invoked within a doPrivileged block.
*
* @param clazz The class for which to obtain the constructor.
* @return privileged action to obtain the constructor.
* The action could return {@code null} if the constructor is not present.
* @see AccessController#doPrivileged(java.security.PrivilegedAction)
*/
public static PrivilegedAction<Constructor> getStringConstructorPA(final Class<?> clazz) {
return new PrivilegedAction<Constructor>() {
@Override
public Constructor run() {
try {
return clazz.getConstructor(String.class);
} catch (final SecurityException e) {
throw e;
} catch (final Exception e) {
return null;
}
}
};
}
/**
* Get privileged action to obtain declared constructors of given class.
* If run using security manager, the returned privileged action
* must be invoked within a doPrivileged block.
*
* @param clazz The class for which to obtain the constructors.
* @return privileged action to obtain the array of constructors.
* @see AccessController#doPrivileged(java.security.PrivilegedAction)
*/
public static PrivilegedAction<Constructor<?>[]> getDeclaredConstructorsPA(final Class<?> clazz) {
return new PrivilegedAction<Constructor<?>[]>() {
@Override
public Constructor<?>[] run() {
return clazz.getDeclaredConstructors();
}
};
}
/**
* Get privileged action to obtain declared constructor of given class with given parameters.
* If run using security manager, the returned privileged action must be invoked within a doPrivileged block.
*
* @param clazz The class for which to obtain the constructor.
* @param params constructor parameters.
* @return privileged action to obtain the constructor or {@code null}, when constructor with given parameters
* is not found.
* @see AccessController#doPrivileged(java.security.PrivilegedAction)
*/
public static PrivilegedAction<Constructor<?>> getDeclaredConstructorPA(final Class<?> clazz, final Class<?>... params) {
return new PrivilegedAction<Constructor<?>>() {
@Override
public Constructor<?> run() {
try {
return clazz.getDeclaredConstructor(params);
} catch (NoSuchMethodException e) {
return null;
}
}
};
}
/**
* Returns collection of all annotation types attached to a given annotated element that have the provided meta
* annotation attached.
*
* @param annotatedElement annotated element.
* @param metaAnnotation meta annotation attached to the annotation types we are looking for (if null, annotation
* types of all attached annotations will be returned).
* @return list of annotation types with a given meta annotation
*/
public static Collection<Class<? extends Annotation>> getAnnotationTypes(final AnnotatedElement annotatedElement,
final Class<? extends Annotation> metaAnnotation) {
final Set<Class<? extends Annotation>> result = Collections.newSetFromMap(new IdentityHashMap<>());
for (final Annotation a : annotatedElement.getAnnotations()) {
final Class<? extends Annotation> aType = a.annotationType();
if (metaAnnotation == null || aType.getAnnotation(metaAnnotation) != null) {
result.add(aType);
}
}
return result;
}
/**
* Determine whether a given method is {@code getter}.
*
* @param method method to be examined.
* @return {@code true} if the method is {@code getter}, {@code false} otherwise.
*/
public static boolean isGetter(final Method method) {
if (method.getParameterTypes().length == 0
&& Modifier.isPublic(method.getModifiers())) {
final String methodName = method.getName();
if (methodName.startsWith("get") && methodName.length() > 3) {
return !void.class.equals(method.getReturnType());
} else if (methodName.startsWith("is") && methodName.length() > 2) {
return boolean.class.equals(method.getReturnType()) || Boolean.class.equals(method.getReturnType());
}
}
return false;
}
/**
* Create a {@link javax.ws.rs.core.GenericType generic type} information for a given
* Java {@code instance}.
* <p>
* If the supplied instance is an instance of {@link javax.ws.rs.core.GenericEntity}, the generic type
* information will be computed using the {@link javax.ws.rs.core.GenericEntity#getType()}
* information. Otherwise the {@code instance.getClass()} will be used.
* </p>
*
* @param instance Java instance for which the {@code GenericType} description should be created.
* @return {@code GenericType} describing the Java {@code instance}.
*/
public static GenericType genericTypeFor(final Object instance) {
final GenericType genericType;
if (instance instanceof GenericEntity) {
genericType = new GenericType(((GenericEntity) instance).getType());
} else {
genericType = (instance == null) ? null : new GenericType(instance.getClass());
}
return genericType;
}
/**
* Determine whether a given method is {@code setter}.
*
* @param method method to be examined.
* @return {@code true} if the method is {@code setter}, {@code false} otherwise.
*/
public static boolean isSetter(final Method method) {
return Modifier.isPublic(method.getModifiers())
&& void.class.equals(method.getReturnType())
&& method.getParameterTypes().length == 1
&& method.getName().startsWith("set");
}
/**
* Determine property (field) name from given getter/setter method.
*
* @param method method to be examined.
* @return property (field) name.
*/
public static String getPropertyName(final Method method) {
if (!isGetter(method) && !isSetter(method)) {
throw new IllegalArgumentException(LocalizationMessages.METHOD_NOT_GETTER_NOR_SETTER());
}
final String methodName = method.getName();
final int offset = methodName.startsWith("is") ? 2 : 3;
final char[] chars = methodName.toCharArray();
chars[offset] = Character.toLowerCase(chars[offset]);
return new String(chars, offset, chars.length - offset);
}
/**
* Determine the most specific type from given set.
*
* @param contractTypes to be taken into account.
* @return the most specific type.
*/
public static Class<?> theMostSpecificTypeOf(final Set<Type> contractTypes) {
Class<?> result = null;
for (final Type t : contractTypes) {
final Class<?> next = (Class<?>) t;
if (result == null) {
result = next;
} else {
if (result.isAssignableFrom(next)) {
result = next;
}
}
}
return result;
}
/**
* A tuple consisting of a concrete class and a declaring class that declares a
* generic interface type.
*/
public static class DeclaringClassInterfacePair {
/**
* Concrete class.
*/
public final Class<?> concreteClass;
/**
* Declaring class.
*/
public final Class<?> declaringClass;
/**
* Generic interface type.
*/
public final Type genericInterface;
private DeclaringClassInterfacePair(final Class<?> concreteClass,
final Class<?> declaringClass,
final Type genericInterface) {
this.concreteClass = concreteClass;
this.declaringClass = declaringClass;
this.genericInterface = genericInterface;
}
}
/**
* Get the parameterized class arguments for a declaring class that