-
Notifications
You must be signed in to change notification settings - Fork 53
Expand file tree
/
Copy pathTypes.java
More file actions
3868 lines (3531 loc) · 125 KB
/
Types.java
File metadata and controls
3868 lines (3531 loc) · 125 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
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
/*
* #%L
* SciJava Common shared library for SciJava software.
* %%
* Copyright (C) 2009 - 2026 SciJava developers.
* %%
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDERS OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
* #L%
*/
// Portions of this class were adapted from the
// org.apache.commons.lang3.reflect.TypeUtils and
// org.apache.commons.lang3.Validate classes of
// Apache Commons Lang 3.4, which is distributed
// under the Apache 2 license.
// See lines below starting with "BEGIN FORK OF APACHE COMMONS LANG".
//
// Portions of this class were adapted from the GenTyRef project
// by Wouter Coekaerts, which is distributed under the Apache 2 license.
// See lines below starting with "BEGIN FORK OF GENTYREF".
//
// See NOTICE.txt for further details on third-party licenses.
package org.scijava.util;
import java.io.File;
import java.io.Serializable;
import java.lang.reflect.Array;
import java.lang.reflect.Field;
import java.lang.reflect.GenericArrayType;
import java.lang.reflect.GenericDeclaration;
import java.lang.reflect.Method;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.lang.reflect.TypeVariable;
import java.lang.reflect.WildcardType;
import java.net.MalformedURLException;
import java.net.URL;
import java.security.CodeSource;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Set;
import org.scijava.Context;
/**
* Utility class for working with generic types, fields and methods.
* <p>
* Logic and inspiration were drawn from the following excellent libraries:
* </p>
* <ul>
* <li>Google Guava's {@code com.google.common.reflect} package.</li>
* <li>Apache Commons Lang 3's {@code org.apache.commons.lang3.reflect} package.
* </li>
* <li><a href="https://github.com/coekarts/gentyref">GenTyRef</a> (Generic Type
* Reflector), a library for runtime generic type introspection.</li>
* </ul>
* <p>
* All three of these libraries contain fantastic generics-related logic, but
* none of the three contained everything that SciJava needed for all its use
* cases. Hence, we have drawn from sources as needed to create a unified
* generics API for use from SciJava applications. See in particular the
* <a href="https://github.com/scijava/scijava-ops">SciJava Ops</a> project,
* which utilizes these functions heavily.
* </p>
* <p>
* NB: The <a href=
* "https://javadoc.scijava.org/Apache-Commons-Lang/org/apache/commons/lang3/reflect/TypeUtils.html">
* <code>org.apache.commons.reflect.TypeUtils</code></a> class of
* <a href="https://commons.apache.org/proper/commons-lang/">Apache Commons
* Lang</a> version 3.4 is forked internally within this class. We did this for
* two reasons: 1) to avoid bringing in the whole of Apache Commons Lang as a
* dependency; and 2) to fix an infinite recursion bug in the
* {@code TypeUtils.toString(Type)} method.
* </p>
*
* @author Curtis Rueden
* @author Gabe Selzer
*/
public final class Types {
private Types() {
// NB: Prevent instantiation of utility class.
}
/**
* Loads the class with the given name, using the current thread's context
* class loader, or null if it cannot be loaded.
*
* @param name The name of the class to load.
* @return The loaded class, or null if the class could not be loaded.
* @see #load(String, ClassLoader, boolean)
*/
public static Class<?> load(final String name) {
return load(name, null, true);
}
/**
* Loads the class with the given name, using the specified
* {@link ClassLoader}, or null if it cannot be loaded.
*
* @param name The name of the class to load.
* @param classLoader The class loader with which to load the class; if null,
* the current thread's context class loader will be used.
* @return The loaded class, or null if the class could not be loaded.
* @see #load(String, ClassLoader, boolean)
*/
public static Class<?> load(final String name,
final ClassLoader classLoader)
{
return load(name, classLoader, true);
}
/**
* Loads the class with the given name, using the current thread's context
* class loader.
*
* @param className the name of the class to load.
* @param quietly Whether to return {@code null} (rather than throwing
* {@link IllegalArgumentException}) if something goes wrong loading
* the class.
* @return The loaded class, or {@code null} if the class could not be loaded
* and the {@code quietly} flag is set.
* @see #load(String, ClassLoader, boolean)
* @throws IllegalArgumentException If the class cannot be loaded and the
* {@code quietly} flag is not set.
*/
public static Class<?> load(final String className, final boolean quietly) {
return load(className, null, quietly);
}
/**
* Loads the class with the given name, using the specified
* {@link ClassLoader}, or null if it cannot be loaded.
* <p>
* This method is capable of parsing several different class name syntaxes. In
* particular, array classes (including primitives) represented using either
* square brackets or internal Java array name syntax are supported. Examples:
* </p>
* <ul>
* <li>{@code boolean} is loaded as {@code boolean.class}</li>
* <li>{@code Z} is loaded as {@code boolean.class}</li>
* <li>{@code double[]} is loaded as {@code double[].class}</li>
* <li>{@code string[]} is loaded as {@code java.lang.String.class}</li>
* <li>{@code [F} is loaded as {@code float[].class}</li>
* </ul>
*
* @param name The name of the class to load.
* @param classLoader The class loader with which to load the class; if null,
* the current thread's context class loader will be used.
* @param quietly Whether to return {@code null} (rather than throwing
* {@link IllegalArgumentException}) if something goes wrong loading
* the class
* @return The loaded class, or {@code null} if the class could not be loaded
* and the {@code quietly} flag is set.
* @throws IllegalArgumentException If the class cannot be loaded and the
* {@code quietly} flag is not set.
*/
public static Class<?> load(final String name, final ClassLoader classLoader,
final boolean quietly)
{
// handle primitive types
if (name.equals("Z") || name.equals("boolean")) return boolean.class;
if (name.equals("B") || name.equals("byte")) return byte.class;
if (name.equals("C") || name.equals("char")) return char.class;
if (name.equals("D") || name.equals("double")) return double.class;
if (name.equals("F") || name.equals("float")) return float.class;
if (name.equals("I") || name.equals("int")) return int.class;
if (name.equals("J") || name.equals("long")) return long.class;
if (name.equals("S") || name.equals("short")) return short.class;
if (name.equals("V") || name.equals("void")) return void.class;
// handle built-in class shortcuts
final String className;
if (name.equals("string")) className = "java.lang.String";
else className = name;
// handle source style arrays (e.g.: "java.lang.String[]")
if (name.endsWith("[]")) {
final String elementClassName = name.substring(0, name.length() - 2);
return arrayOrNull(load(elementClassName, classLoader));
}
// handle non-primitive internal arrays (e.g.: "[Ljava.lang.String;")
if (name.startsWith("[L") && name.endsWith(";")) {
final String elementClassName = name.substring(2, name.length() - 1);
return arrayOrNull(load(elementClassName, classLoader));
}
// handle other internal arrays (e.g.: "[I", "[[I", "[[Ljava.lang.String;")
if (name.startsWith("[")) {
final String elementClassName = name.substring(1);
return arrayOrNull(load(elementClassName, classLoader));
}
// load the class!
try {
final ClassLoader cl = //
classLoader != null ? classLoader : Context.getClassLoader();
return cl.loadClass(className);
}
catch (final Throwable t) {
// NB: Do not allow any failure to load the class to crash us.
// Not ClassNotFoundException.
// Not NoClassDefFoundError.
// Not UnsupportedClassVersionError!
if (quietly) return null;
throw iae(t, "Cannot load class: " + className);
}
}
/**
* Gets the base location of the given class.
*
* @param c The class whose location is desired.
* @return URL pointing to the class, or null if the location could not be
* determined.
* @see #location(Class, boolean)
*/
public static URL location(final Class<?> c) {
return location(c, true);
}
/**
* Gets the base location of the given class.
* <p>
* If the class is directly on the file system (e.g.,
* "/path/to/my/package/MyClass.class") then it will return the base directory
* (e.g., "file:/path/to").
* </p>
* <p>
* If the class is within a JAR file (e.g.,
* "/path/to/my-jar.jar!/my/package/MyClass.class") then it will return the
* path to the JAR (e.g., "file:/path/to/my-jar.jar").
* </p>
*
* @param c The class whose location is desired.
* @param quietly Whether to return {@code null} (rather than throwing
* {@link IllegalArgumentException}) if something goes wrong
* determining the location.
* @return URL pointing to the class, or null if the location could not be
* determined and the {@code quietly} flag is set.
* @throws IllegalArgumentException If the location cannot be determined and
* the {@code quietly} flag is not set.
* @see FileUtils#urlToFile(URL) to convert the result to a {@link File}.
*/
public static URL location(final Class<?> c, final boolean quietly) {
Exception cause = null;
String why = null;
// try the easy way first
try {
final CodeSource codeSource = c.getProtectionDomain().getCodeSource();
if (codeSource != null) {
final URL location = codeSource.getLocation();
if (location != null) return location;
why = "null code source location";
}
else why = "null code source";
}
catch (final SecurityException exc) {
// NB: Cannot access protection domain.
cause = exc;
why = "cannot access protection domain";
}
// NB: The easy way failed, so we try the hard way. We ask for the class
// itself as a resource, then strip the class's path from the URL string,
// leaving the base path.
// get the class's raw resource path
final URL classResource = c.getResource(c.getSimpleName() + ".class");
if (classResource == null) {
// cannot find class resource
if (quietly) return null;
throw iae(cause, "No class resource for class: " + name(c), why);
}
final String url = classResource.toString();
final String suffix = c.getCanonicalName().replace('.', '/') + ".class";
if (!url.endsWith(suffix)) {
// weird URL
if (quietly) return null;
throw iae(cause, "Unsupported URL format: " + url, why);
}
// strip the class's path from the URL string
final String base = url.substring(0, url.length() - suffix.length());
String path = base;
// remove the "jar:" prefix and "!/" suffix, if present
if (path.startsWith("jar:")) path = path.substring(4, path.length() - 2);
try {
return new URL(path);
}
catch (final MalformedURLException e) {
if (quietly) return null;
throw iae(e, "Malformed URL", why);
}
}
/**
* Gets a string representation of the given type.
*
* @param t Type whose name is desired.
* @return The name of the given type.
*/
public static String name(final Type t) {
if (t instanceof Class) {
final Class<?> c = (Class<?>) t;
return c.isArray() ? (name(component(c)) + "[]") : c.getName();
}
return t.toString();
}
/**
* Gets the (first) raw class of the given type.
* <ul>
* <li>If the type is a {@code Class} itself, the type itself is returned.
* </li>
* <li>If the type is a {@link ParameterizedType}, the raw type of the
* parameterized type is returned.</li>
* <li>If the type is a {@link GenericArrayType}, the returned type is the
* corresponding array class. For example: {@code List<Integer>[] => List[]}.
* </li>
* <li>If the type is a type variable or wildcard type, the raw type of the
* first upper bound is returned. For example:
* {@code <X extends Foo & Bar> => Foo}.</li>
* </ul>
* <p>
* If you want <em>all</em> raw classes of the given type, use {@link #raws}.
* </p>
*
* @param type The type from which to discern the (first) raw class.
* @return The type's first raw class.
*/
public static Class<?> raw(final Type type) {
if (type == null) return null;
if (type instanceof Class) return (Class<?>) type;
if (type instanceof GenericArrayType)
return array(raw(((GenericArrayType) type).getGenericComponentType()));
final List<Class<?>> c = raws(type);
if (c == null || c.size() == 0) return null;
return c.get(0);
}
/**
* Gets all raw classes corresponding to the given type.
* <p>
* For example, a type parameter {@code A extends Number & Iterable} will
* return both {@link Number} and {@link Iterable} as its raw classes.
* </p>
*
* @param type The type from which to discern the raw classes.
* @return List of the type's raw classes.
* @see #raw
*/
public static List<Class<?>> raws(final Type type) {
if (type == null) return null;
return GenericTypeReflector.getUpperBoundClassAndInterfaces(type);
}
public static boolean isBoolean(final Class<?> type) {
return type == boolean.class || Boolean.class.isAssignableFrom(type);
}
public static boolean isByte(final Class<?> type) {
return type == byte.class || Byte.class.isAssignableFrom(type);
}
public static boolean isCharacter(final Class<?> type) {
return type == char.class || Character.class.isAssignableFrom(type);
}
public static boolean isDouble(final Class<?> type) {
return type == double.class || Double.class.isAssignableFrom(type);
}
public static boolean isFloat(final Class<?> type) {
return type == float.class || Float.class.isAssignableFrom(type);
}
public static boolean isInteger(final Class<?> type) {
return type == int.class || Integer.class.isAssignableFrom(type);
}
public static boolean isLong(final Class<?> type) {
return type == long.class || Long.class.isAssignableFrom(type);
}
public static boolean isShort(final Class<?> type) {
return type == short.class || Short.class.isAssignableFrom(type);
}
public static boolean isNumber(final Class<?> type) {
return Number.class.isAssignableFrom(type) || type == byte.class ||
type == double.class || type == float.class || type == int.class ||
type == long.class || type == short.class;
}
public static boolean isText(final Class<?> type) {
return String.class.isAssignableFrom(type) || isCharacter(type);
}
/**
* Returns the non-primitive {@link Class} closest to the given type.
* <p>
* Specifically, the following type conversions are done:
* </p>
* <ul>
* <li>boolean.class becomes Boolean.class</li>
* <li>byte.class becomes Byte.class</li>
* <li>char.class becomes Character.class</li>
* <li>double.class becomes Double.class</li>
* <li>float.class becomes Float.class</li>
* <li>int.class becomes Integer.class</li>
* <li>long.class becomes Long.class</li>
* <li>short.class becomes Short.class</li>
* <li>void.class becomes Void.class</li>
* </ul>
* <p>
* All other types are unchanged.
* </p>
*/
public static <T> Class<T> box(final Class<T> type) {
final Class<?> destType;
if (type == boolean.class) destType = Boolean.class;
else if (type == byte.class) destType = Byte.class;
else if (type == char.class) destType = Character.class;
else if (type == double.class) destType = Double.class;
else if (type == float.class) destType = Float.class;
else if (type == int.class) destType = Integer.class;
else if (type == long.class) destType = Long.class;
else if (type == short.class) destType = Short.class;
else if (type == void.class) destType = Void.class;
else destType = type;
@SuppressWarnings("unchecked")
final Class<T> result = (Class<T>) destType;
return result;
}
/**
* Returns the primitive {@link Class} closest to the given type.
* <p>
* Specifically, the following type conversions are done:
* </p>
* <ul>
* <li>Boolean.class becomes boolean.class</li>
* <li>Byte.class becomes byte.class</li>
* <li>Character.class becomes char.class</li>
* <li>Double.class becomes double.class</li>
* <li>Float.class becomes float.class</li>
* <li>Integer.class becomes int.class</li>
* <li>Long.class becomes long.class</li>
* <li>Short.class becomes short.class</li>
* <li>Void.class becomes void.class</li>
* </ul>
* <p>
* All other types are unchanged.
* </p>
*/
public static <T> Class<T> unbox(final Class<T> type) {
final Class<?> destType;
if (type == Boolean.class) destType = boolean.class;
else if (type == Byte.class) destType = byte.class;
else if (type == Character.class) destType = char.class;
else if (type == Double.class) destType = double.class;
else if (type == Float.class) destType = float.class;
else if (type == Integer.class) destType = int.class;
else if (type == Long.class) destType = long.class;
else if (type == Short.class) destType = short.class;
else if (type == Void.class) destType = void.class;
else destType = type;
@SuppressWarnings("unchecked")
final Class<T> result = (Class<T>) destType;
return result;
}
/**
* Gets the "null" value for the given type. For non-primitives, this will
* actually be null. For primitives, it will be zero for numeric types, false
* for boolean, and the null character for char.
*/
public static <T> T nullValue(final Class<T> type) {
final Object defaultValue;
if (type == boolean.class) defaultValue = false;
else if (type == byte.class) defaultValue = (byte) 0;
else if (type == char.class) defaultValue = '\0';
else if (type == double.class) defaultValue = 0d;
else if (type == float.class) defaultValue = 0f;
else if (type == int.class) defaultValue = 0;
else if (type == long.class) defaultValue = 0L;
else if (type == short.class) defaultValue = (short) 0;
else defaultValue = null;
@SuppressWarnings("unchecked")
final T result = (T) defaultValue;
return result;
}
/**
* Gets the field with the specified name, of the given class, or superclass
* thereof.
* <p>
* Unlike {@link Class#getField(String)}, this method will return fields of
* any visibility, not just {@code public}. And unlike
* {@link Class#getDeclaredField(String)}, it will do so recursively,
* returning the first field of the given name from the class's superclass
* hierarchy.
* </p>
* <p>
* Note that this method does not guarantee that the returned field is
* accessible; if the field is not {@code public}, calling code will need to
* use {@link Field#setAccessible(boolean)} in order to manipulate the field's
* contents.
* </p>
*
* @param c The class (or subclass thereof) containing the desired field.
* @param name
* @return The first field with the given name in the class's superclass
* hierarchy.
* @throws IllegalArgumentException if the specified class does not contain a
* method with the given name
*/
public static Field field(final Class<?> c, final String name) {
if (c == null) throw iae("No such field: " + name);
try {
return c.getDeclaredField(name);
}
catch (final NoSuchFieldException e) {}
return field(c.getSuperclass(), name);
}
/**
* Gets the method with the specified name and argument types, of the given
* class, or superclass thereof.
* <p>
* Unlike {@link Class#getMethod(String, Class[])}, this method will return
* methods of any visibility, not just {@code public}. And unlike
* {@link Class#getDeclaredMethod(String, Class[])}, it will do so
* recursively, returning the first method of the given name and argument
* types from the class's superclass hierarchy.
* </p>
* <p>
* Note that this method does not guarantee that the returned method is
* accessible; if the method is not {@code public}, calling code will need to
* use {@link Method#setAccessible(boolean)} in order to invoke the method.
* </p>
*
* @param c The class (or subclass thereof) containing the desired method.
* @param name Name of the method.
* @param parameterTypes Types of the method parameters.
* @return The first method with the given name and argument types in the
* class's superclass hierarchy.
* @throws IllegalArgumentException If the specified class does not contain a
* method with the given name and argument types.
*/
public static Method method(final Class<?> c, final String name,
final Class<?>... parameterTypes)
{
if (c == null) throw iae("No such field: " + name);
try {
return c.getDeclaredMethod(name, parameterTypes);
}
catch (final NoSuchMethodException exc) {}
return method(c.getSuperclass(), name, parameterTypes);
}
/**
* Gets the array class corresponding to the given element type.
* <p>
* For example, {@code arrayType(double.class)} returns {@code double[].class}
* .
* </p>
*
* @param componentType The type of elements which the array possesses
* @throws IllegalArgumentException if the type cannot be the component type
* of an array (this is the case e.g. for {@code void.class}).
*/
public static Class<?> array(final Class<?> componentType) {
if (componentType == null) return null;
// NB: It appears the reflection API has no built-in way to do this.
// So unfortunately, we must allocate a new object and then inspect it.
return Array.newInstance(componentType, 0).getClass();
}
/**
* Gets the array class corresponding to the given element type and
* dimensionality.
* <p>
* For example, {@code arrayType(double.class, 2)} returns
* {@code double[][].class} .
* </p>
*
* @param componentType The type of elements which the array possesses
* @param dim The dimensionality of the array
*/
public static Class<?> array(final Class<?> componentType, final int dim) {
if (dim < 0) throw iae("Negative dimension");
if (dim == 0) return componentType;
return array(array(componentType), dim - 1);
}
/**
* Gets the array type—which might be a {@link Class} or a
* {@link GenericArrayType} depending on the argument—corresponding to
* the given element type.
* <p>
* For example, {@code arrayType(double.class)} returns {@code double[].class}
* .
* </p>
*
* @param componentType The type of elements which the array possesses
* @see #component
*/
public static Type array(final Type componentType) {
if (componentType == null) return null;
if (componentType instanceof Class) {
return array((Class<?>) componentType);
}
return new TypeUtils.GenericArrayTypeImpl(componentType);
}
/**
* Gets the component type of the given array type, or null if not an array.
* <p>
* If you have a {@link Class}, you can call {@link Class#getComponentType()}
* for a narrower return type.
* </p>
* <p>
* This is the opposite of {@link #array(Type)}.
* </p>
*/
public static Type component(final Type type) {
if (type instanceof Class) {
return ((Class<?>) type).getComponentType();
}
if (type instanceof GenericArrayType) {
return ((GenericArrayType) type).getGenericComponentType();
}
return null;
}
/**
* Returns the "safe" generic type of the given field, as viewed from the
* given type. This may be narrower than what {@link Field#getGenericType()}
* returns, if the field is declared in a superclass, or {@code type} has a
* type parameter that is used in the type of the field.
* <p>
* For example, suppose we have the following three classes:
* </p>
*
* <pre>
* public class Thing<T> {
*
* public T thing;
* }
*
* public class NumberThing<N extends Number> extends Thing<N> {}
*
* public class IntegerThing extends NumberThing<Integer> {}
* </pre>
*
* Then this method operates as follows:
*
* <pre>
* field = Types.field(Thing.class, "thing");
*
* field.getType(); // Object
* field.getGenericType(); // T
*
* Types.fieldType(field, Thing.class); // T
* Types.fieldType(field, NumberThing.class); // N extends Number
* Types.fieldType(field, IntegerThing.class); // Integer
* </pre>
*/
public static Type fieldType(final Field field, final Class<?> type) {
final Type wildType = GenericTypeReflector.addWildcardParameters(type);
return GenericTypeReflector.getExactFieldType(field, wildType);
}
/**
* As {@link #fieldType(Field, Class)}, but with respect to the return type of
* the given {@link Method} rather than a {@link Field}.
*/
public static Type methodReturnType(final Method method,
final Class<?> type)
{
final Type wildType = GenericTypeReflector.addWildcardParameters(type);
return GenericTypeReflector.getExactReturnType(method, wildType);
}
/**
* As {@link #fieldType(Field, Class)}, but with respect to the parameter
* types of the given {@link Method} rather than a {@link Field}.
*/
public static Type[] methodParamTypes(final Method method,
final Class<?> type)
{
final Type wildType = GenericTypeReflector.addWildcardParameters(type);
return GenericTypeReflector.getExactParameterTypes(method, wildType);
}
/**
* Gets the given type's {@code n}th type parameter of the specified class.
* <p>
* For example, with class {@code StringList implements List<String>},
* {@code Types.param(StringList.class, Collection.class, 0)} returns
* {@code String}.
* </p>
*/
public static Type param(final Type type, final Class<?> c, final int no) {
return GenericTypeReflector.getTypeParameter(type, //
c.getTypeParameters()[no]);
}
/**
* Discerns whether it would be legal to assign a reference of type
* {@code source} to a reference of type {@code target}.
*
* @param source The type from which assignment is desired.
* @param target The type to which assignment is desired.
* @return True if the source is assignable to the target.
* @throws NullPointerException if {@code target} is null.
* @see Class#isAssignableFrom(Class)
*/
public static boolean isAssignable(final Type source, final Type target) {
return TypeUtils.isAssignable(source, target);
}
/**
* Checks whether the given object can be cast to the specified type.
*
* @return true If the destination class is assignable from the source
* object's class, or if the source object is null and destination
* class is non-null.
* @see #cast(Object, Class)
*/
public static boolean isInstance(final Object obj, final Class<?> dest) {
if (dest == null) return false;
return obj == null || dest.isInstance(obj);
}
/**
* Casts the given object to the specified type, or null if the types are
* incompatible.
*/
public static <T> T cast(final Object src, final Class<T> dest) {
if (!isInstance(src, dest)) return null;
@SuppressWarnings("unchecked")
final T result = (T) src;
return result;
}
/**
* Converts the given string <em>value</em> to an enumeration constant of the
* specified type. For example, {@code enumValue("APPLE", Fruit.class)}
* returns {@code Fruit.APPLE} if such a value is among those of the
* requested enum class.
*
* @param name The value to convert.
* @param dest The type of the enumeration constant.
* @return The converted enumeration constant.
* @throws IllegalArgumentException if the type is not an enumeration type, or
* has no such constant.
*/
public static <T> T enumValue(final String name, final Class<T> dest) {
if (!dest.isEnum()) throw iae("Not an enum type: " + name(dest));
@SuppressWarnings({ "rawtypes", "unchecked" })
final Enum result = Enum.valueOf((Class) dest, name);
@SuppressWarnings("unchecked")
final T typedResult = (T) result;
return typedResult;
}
/**
* Converts the given string <em>label</em> to an enumeration constant of the
* specified type. An enum label is the string returned by the enum constant's
* {@link Object#toString()} method. For example,
* {@code enumFromLabel("Apple", Fruit.class)} returns {@code Fruit.APPLE} if
* {@code Fruit.APPLE.toString()} is implemented to return {@code "Apple"}.
*
* @param label The {@code toString()} result of the desired enum value.
* @param dest The type of the enumeration constant.
* @return The matching enumeration constant.
* @throws IllegalArgumentException if the type is not an enumeration type, or
* has no constant with the given label.
*/
public static <T> T enumFromLabel(final String label, final Class<T> dest) {
final T[] values = dest.getEnumConstants();
if (values == null) throw iae("Not an enum type: " + name(dest));
for (T value : values) {
if (Objects.equals(label, value.toString())) return value;
}
throw iae("Enum class " + dest.getName() + " has no such label: " + label);
}
/**
* Converts the given string value or label to an enumeration constant of the
* specified type.
* <p>
* If the string matches one of the enum values directly, that value will be
* returned via {@link #enumValue(String, Class)}. Otherwise, the result of
* {@link #enumFromLabel} is returned.
* </p>
*
* @param s The name or label of the desired enum value.
* @param dest The type of the enumeration constant.
* @return The matching enumeration constant.
* @throws IllegalArgumentException if the type is not an enumeration type,
* or has no such constant with the given name nor label.
*/
public static <T> T enumFromString(final String s, final Class<T> dest) {
if (!dest.isEnum()) throw iae("Not an enum type: " + name(dest));
try {
return enumValue(s, dest);
}
catch (final IllegalArgumentException exc) {
// NB: No action needed.
}
try {
return enumFromLabel(s, dest);
}
catch (final IllegalArgumentException exc) {
// NB: No action needed.
}
throw iae("Enum class " + dest.getName() + " has no such value nor label: " + s);
}
/**
* Creates a new {@link ParameterizedType} of the given class together with
* the specified type arguments.
*
* @param rawType The class of the {@link ParameterizedType}.
* @param typeArgs The type arguments to use in parameterizing it.
* @return The newly created {@link ParameterizedType}.
*/
public static ParameterizedType parameterize(final Class<?> rawType,
final Type... typeArgs)
{
return parameterizeWithOwner(null, rawType, typeArgs);
}
/**
* Creates a new {@link ParameterizedType} of the given class together with
* the specified type arguments.
*
* @param ownerType The owner type of the parameterized class.
* @param rawType The class of the {@link ParameterizedType}.
* @param typeArgs The type arguments to use in parameterizing it.
* @return The newly created {@link ParameterizedType}.
*/
public static ParameterizedType parameterizeWithOwner(final Type ownerType,
final Class<?> rawType, final Type... typeArgs)
{
return TypeUtils.parameterizeWithOwner(ownerType, rawType, typeArgs);
}
/**
* Creates a new {@link WildcardType} with no upper or lower bounds (i.e.,
* {@code ?}).
*
* @return The newly created {@link WildcardType}.
*/
public static WildcardType wildcard() {
return wildcard((Type) null, (Type) null);
}
/**
* Creates a new {@link WildcardType} with the given upper and/or lower bound.
*
* @param upperBound Upper bound of the wildcard, or null for none.
* @param lowerBound Lower bound of the wildcard, or null for none.
* @return The newly created {@link WildcardType}.
*/
public static WildcardType wildcard(final Type upperBound,
final Type lowerBound)
{
return new TypeUtils.WildcardTypeImpl(upperBound, lowerBound);
}
/**
* Creates a new {@link WildcardType} with the given upper and/or lower
* bounds.
*
* @param upperBounds Upper bounds of the wildcard, or null for none.
* @param lowerBounds Lower bounds of the wildcard, or null for none.
* @return The newly created {@link WildcardType}.
*/
public static WildcardType wildcard(final Type[] upperBounds,
final Type[] lowerBounds)
{
return new TypeUtils.WildcardTypeImpl(upperBounds, lowerBounds);
}
/**
* Learn, recursively, whether any of the type parameters associated with
* {@code type} are bound to variables.
*
* @param type the type to check for type variables
* @return boolean
*/
public static boolean containsTypeVars(final Type type) {
return TypeUtils.containsTypeVariables(type);
}
/**
* Gets the type arguments of a class/interface based on a subtype. For
* instance, this method will determine that both of the parameters for the
* interface {@link Map} are {@link Object} for the subtype
* {@link java.util.Properties Properties} even though the subtype does not
* directly implement the {@code Map} interface.
* <p>
* This method returns {@code null} if {@code type} is not assignable to
* {@code toClass}. It returns an empty map if none of the classes or
* interfaces in its inheritance hierarchy specify any type arguments.
* </p>
* <p>
* A side effect of this method is that it also retrieves the type arguments
* for the classes and interfaces that are part of the hierarchy between
* {@code type} and {@code toClass}. So with the above example, this method
* will also determine that the type arguments for {@link java.util.Hashtable
* Hashtable} are also both {@code Object}. In cases where the interface
* specified by {@code toClass} is (indirectly) implemented more than once
* (e.g. where {@code toClass} specifies the interface
* {@link java.lang.Iterable Iterable} and {@code type} specifies a
* parameterized type that implements both {@link java.util.Set Set} and
* {@link java.util.Collection Collection}), this method will look at the
* inheritance hierarchy of only one of the implementations/subclasses; the
* first interface encountered that isn't a subinterface to one of the others
* in the {@code type} to {@code toClass} hierarchy.
* </p>
*
* @param type the type from which to determine the type parameters of
* {@code toClass}
* @param toClass the class whose type parameters are to be determined based
* on the subtype {@code type}
* @return a {@code Map} of the type assignments for the type variables in
* each type in the inheritance hierarchy from {@code type} to
* {@code toClass} inclusive.
*/
public static Map<TypeVariable<?>, Type> args(final Type type,
final Class<?> toClass)
{
return TypeUtils.getTypeArguments(type, toClass);
}
/**
* Tries to determine the type arguments of a class/interface based on a super
* parameterized type's type arguments. This method is the inverse of
* {@link #args(Type, Class)} which gets a class/interface's type arguments
* based on a subtype. It is far more limited in determining the type
* arguments for the subject class's type variables in that it can only
* determine those parameters that map from the subject {@link Class} object
* to the supertype.
* <p>
* Example: {@link java.util.TreeSet TreeSet} sets its parameter as the
* parameter for {@link java.util.NavigableSet NavigableSet}, which in turn
* sets the parameter of {@link java.util.SortedSet}, which in turn sets the
* parameter of {@link Set}, which in turn sets the parameter of
* {@link java.util.Collection}, which in turn sets the parameter of
* {@link java.lang.Iterable}. Since {@code TreeSet}'s parameter maps
* (indirectly) to {@code Iterable}'s parameter, it will be able to determine
* that based on the super type {@code Iterable<? extends
* Map<Integer, ? extends Collection<?>>>}, the parameter of {@code TreeSet}
* is {@code ? extends Map<Integer, ? extends Collection<?>>}.
* </p>
*
* @param c the class whose type parameters are to be determined, not
* {@code null}
* @param superType the super type from which {@code c}'s type arguments are
* to be determined, not {@code null}
* @return a {@code Map} of the type assignments that could be determined for