-
Notifications
You must be signed in to change notification settings - Fork 10.9k
/
TypeToken.java
1446 lines (1308 loc) · 52.2 KB
/
TypeToken.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) 2006 The Guava Authors
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
* in compliance with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License
* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
* or implied. See the License for the specific language governing permissions and limitations under
* the License.
*/
package com.google.common.reflect;
import static com.google.common.base.Preconditions.checkArgument;
import static com.google.common.base.Preconditions.checkNotNull;
import static com.google.common.base.Preconditions.checkState;
import com.google.common.annotations.Beta;
import com.google.common.annotations.VisibleForTesting;
import com.google.common.base.Joiner;
import com.google.common.base.Predicate;
import com.google.common.collect.FluentIterable;
import com.google.common.collect.ForwardingSet;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.ImmutableSet;
import com.google.common.collect.Maps;
import com.google.common.collect.Ordering;
import com.google.common.primitives.Primitives;
import com.google.errorprone.annotations.CanIgnoreReturnValue;
import java.io.Serializable;
import java.lang.reflect.Constructor;
import java.lang.reflect.GenericArrayType;
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.util.ArrayList;
import java.util.Arrays;
import java.util.Comparator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.checkerframework.checker.nullness.compatqual.MonotonicNonNullDecl;
import org.checkerframework.checker.nullness.compatqual.NullableDecl;
/**
* A {@link Type} with generics.
*
* <p>Operations that are otherwise only available in {@link Class} are implemented to support
* {@code Type}, for example {@link #isSubtypeOf}, {@link #isArray} and {@link #getComponentType}.
* It also provides additional utilities such as {@link #getTypes}, {@link #resolveType}, etc.
*
* <p>There are three ways to get a {@code TypeToken} instance:
*
* <ul>
* <li>Wrap a {@code Type} obtained via reflection. For example: {@code
* TypeToken.of(method.getGenericReturnType())}.
* <li>Capture a generic type with a (usually anonymous) subclass. For example:
* <pre>{@code
* new TypeToken<List<String>>() {}
* }</pre>
* <p>Note that it's critical that the actual type argument is carried by a subclass. The
* following code is wrong because it only captures the {@code <T>} type variable of the
* {@code listType()} method signature; while {@code <String>} is lost in erasure:
* <pre>{@code
* class Util {
* static <T> TypeToken<List<T>> listType() {
* return new TypeToken<List<T>>() {};
* }
* }
*
* TypeToken<List<String>> stringListType = Util.<String>listType();
* }</pre>
* <li>Capture a generic type with a (usually anonymous) subclass and resolve it against a context
* class that knows what the type parameters are. For example:
* <pre>{@code
* abstract class IKnowMyType<T> {
* TypeToken<T> type = new TypeToken<T>(getClass()) {};
* }
* new IKnowMyType<String>() {}.type => String
* }</pre>
* </ul>
*
* <p>{@code TypeToken} is serializable when no type variable is contained in the type.
*
* <p>Note to Guice users: {@code} TypeToken is similar to Guice's {@code TypeLiteral} class except
* that it is serializable and offers numerous additional utility methods.
*
* @author Bob Lee
* @author Sven Mawson
* @author Ben Yu
* @since 12.0
*/
@Beta
@SuppressWarnings("serial") // SimpleTypeToken is the serialized form.
public abstract class TypeToken<T> extends TypeCapture<T> implements Serializable {
private final Type runtimeType;
/** Resolver for resolving parameter and field types with {@link #runtimeType} as context. */
@MonotonicNonNullDecl private transient TypeResolver invariantTypeResolver;
/** Resolver for resolving covariant types with {@link #runtimeType} as context. */
@MonotonicNonNullDecl private transient TypeResolver covariantTypeResolver;
/**
* Constructs a new type token of {@code T}.
*
* <p>Clients create an empty anonymous subclass. Doing so embeds the type parameter in the
* anonymous class's type hierarchy so we can reconstitute it at runtime despite erasure.
*
* <p>For example:
*
* <pre>{@code
* TypeToken<List<String>> t = new TypeToken<List<String>>() {};
* }</pre>
*/
protected TypeToken() {
this.runtimeType = capture();
checkState(
!(runtimeType instanceof TypeVariable),
"Cannot construct a TypeToken for a type variable.\n"
+ "You probably meant to call new TypeToken<%s>(getClass()) "
+ "that can resolve the type variable for you.\n"
+ "If you do need to create a TypeToken of a type variable, "
+ "please use TypeToken.of() instead.",
runtimeType);
}
/**
* Constructs a new type token of {@code T} while resolving free type variables in the context of
* {@code declaringClass}.
*
* <p>Clients create an empty anonymous subclass. Doing so embeds the type parameter in the
* anonymous class's type hierarchy so we can reconstitute it at runtime despite erasure.
*
* <p>For example:
*
* <pre>{@code
* abstract class IKnowMyType<T> {
* TypeToken<T> getMyType() {
* return new TypeToken<T>(getClass()) {};
* }
* }
*
* new IKnowMyType<String>() {}.getMyType() => String
* }</pre>
*/
protected TypeToken(Class<?> declaringClass) {
Type captured = super.capture();
if (captured instanceof Class) {
this.runtimeType = captured;
} else {
this.runtimeType = TypeResolver.covariantly(declaringClass).resolveType(captured);
}
}
private TypeToken(Type type) {
this.runtimeType = checkNotNull(type);
}
/** Returns an instance of type token that wraps {@code type}. */
public static <T> TypeToken<T> of(Class<T> type) {
return new SimpleTypeToken<T>(type);
}
/** Returns an instance of type token that wraps {@code type}. */
public static TypeToken<?> of(Type type) {
return new SimpleTypeToken<>(type);
}
/**
* Returns the raw type of {@code T}. Formally speaking, if {@code T} is returned by {@link
* java.lang.reflect.Method#getGenericReturnType}, the raw type is what's returned by {@link
* java.lang.reflect.Method#getReturnType} of the same method object. Specifically:
*
* <ul>
* <li>If {@code T} is a {@code Class} itself, {@code T} itself is returned.
* <li>If {@code T} is a {@link ParameterizedType}, the raw type of the parameterized type is
* returned.
* <li>If {@code T} is a {@link GenericArrayType}, the returned type is the corresponding array
* class. For example: {@code List<Integer>[] => List[]}.
* <li>If {@code T} is a type variable or a wildcard type, the raw type of the first upper bound
* is returned. For example: {@code <X extends Foo> => Foo}.
* </ul>
*/
public final Class<? super T> getRawType() {
// For wildcard or type variable, the first bound determines the runtime type.
Class<?> rawType = getRawTypes().iterator().next();
@SuppressWarnings("unchecked") // raw type is |T|
Class<? super T> result = (Class<? super T>) rawType;
return result;
}
/** Returns the represented type. */
public final Type getType() {
return runtimeType;
}
/**
* Returns a new {@code TypeToken} where type variables represented by {@code typeParam} are
* substituted by {@code typeArg}. For example, it can be used to construct {@code Map<K, V>} for
* any {@code K} and {@code V} type:
*
* <pre>{@code
* static <K, V> TypeToken<Map<K, V>> mapOf(
* TypeToken<K> keyType, TypeToken<V> valueType) {
* return new TypeToken<Map<K, V>>() {}
* .where(new TypeParameter<K>() {}, keyType)
* .where(new TypeParameter<V>() {}, valueType);
* }
* }</pre>
*
* @param <X> The parameter type
* @param typeParam the parameter type variable
* @param typeArg the actual type to substitute
*/
public final <X> TypeToken<T> where(TypeParameter<X> typeParam, TypeToken<X> typeArg) {
TypeResolver resolver =
new TypeResolver()
.where(
ImmutableMap.of(
new TypeResolver.TypeVariableKey(typeParam.typeVariable), typeArg.runtimeType));
// If there's any type error, we'd report now rather than later.
return new SimpleTypeToken<T>(resolver.resolveType(runtimeType));
}
/**
* Returns a new {@code TypeToken} where type variables represented by {@code typeParam} are
* substituted by {@code typeArg}. For example, it can be used to construct {@code Map<K, V>} for
* any {@code K} and {@code V} type:
*
* <pre>{@code
* static <K, V> TypeToken<Map<K, V>> mapOf(
* Class<K> keyType, Class<V> valueType) {
* return new TypeToken<Map<K, V>>() {}
* .where(new TypeParameter<K>() {}, keyType)
* .where(new TypeParameter<V>() {}, valueType);
* }
* }</pre>
*
* @param <X> The parameter type
* @param typeParam the parameter type variable
* @param typeArg the actual type to substitute
*/
public final <X> TypeToken<T> where(TypeParameter<X> typeParam, Class<X> typeArg) {
return where(typeParam, of(typeArg));
}
/**
* Resolves the given {@code type} against the type context represented by this type. For example:
*
* <pre>{@code
* new TypeToken<List<String>>() {}.resolveType(
* List.class.getMethod("get", int.class).getGenericReturnType())
* => String.class
* }</pre>
*/
public final TypeToken<?> resolveType(Type type) {
checkNotNull(type);
// Being conservative here because the user could use resolveType() to resolve a type in an
// invariant context.
return of(getInvariantTypeResolver().resolveType(type));
}
private TypeToken<?> resolveSupertype(Type type) {
TypeToken<?> supertype = of(getCovariantTypeResolver().resolveType(type));
// super types' type mapping is a subset of type mapping of this type.
supertype.covariantTypeResolver = covariantTypeResolver;
supertype.invariantTypeResolver = invariantTypeResolver;
return supertype;
}
/**
* Returns the generic superclass of this type or {@code null} if the type represents {@link
* Object} or an interface. This method is similar but different from {@link
* Class#getGenericSuperclass}. For example, {@code new TypeToken<StringArrayList>()
* {}.getGenericSuperclass()} will return {@code new TypeToken<ArrayList<String>>() {}}; while
* {@code StringArrayList.class.getGenericSuperclass()} will return {@code ArrayList<E>}, where
* {@code E} is the type variable declared by class {@code ArrayList}.
*
* <p>If this type is a type variable or wildcard, its first upper bound is examined and returned
* if the bound is a class or extends from a class. This means that the returned type could be a
* type variable too.
*/
@NullableDecl
final TypeToken<? super T> getGenericSuperclass() {
if (runtimeType instanceof TypeVariable) {
// First bound is always the super class, if one exists.
return boundAsSuperclass(((TypeVariable<?>) runtimeType).getBounds()[0]);
}
if (runtimeType instanceof WildcardType) {
// wildcard has one and only one upper bound.
return boundAsSuperclass(((WildcardType) runtimeType).getUpperBounds()[0]);
}
Type superclass = getRawType().getGenericSuperclass();
if (superclass == null) {
return null;
}
@SuppressWarnings("unchecked") // super class of T
TypeToken<? super T> superToken = (TypeToken<? super T>) resolveSupertype(superclass);
return superToken;
}
@NullableDecl
private TypeToken<? super T> boundAsSuperclass(Type bound) {
TypeToken<?> token = of(bound);
if (token.getRawType().isInterface()) {
return null;
}
@SuppressWarnings("unchecked") // only upper bound of T is passed in.
TypeToken<? super T> superclass = (TypeToken<? super T>) token;
return superclass;
}
/**
* Returns the generic interfaces that this type directly {@code implements}. This method is
* similar but different from {@link Class#getGenericInterfaces()}. For example, {@code new
* TypeToken<List<String>>() {}.getGenericInterfaces()} will return a list that contains {@code
* new TypeToken<Iterable<String>>() {}}; while {@code List.class.getGenericInterfaces()} will
* return an array that contains {@code Iterable<T>}, where the {@code T} is the type variable
* declared by interface {@code Iterable}.
*
* <p>If this type is a type variable or wildcard, its upper bounds are examined and those that
* are either an interface or upper-bounded only by interfaces are returned. This means that the
* returned types could include type variables too.
*/
final ImmutableList<TypeToken<? super T>> getGenericInterfaces() {
if (runtimeType instanceof TypeVariable) {
return boundsAsInterfaces(((TypeVariable<?>) runtimeType).getBounds());
}
if (runtimeType instanceof WildcardType) {
return boundsAsInterfaces(((WildcardType) runtimeType).getUpperBounds());
}
ImmutableList.Builder<TypeToken<? super T>> builder = ImmutableList.builder();
for (Type interfaceType : getRawType().getGenericInterfaces()) {
@SuppressWarnings("unchecked") // interface of T
TypeToken<? super T> resolvedInterface =
(TypeToken<? super T>) resolveSupertype(interfaceType);
builder.add(resolvedInterface);
}
return builder.build();
}
private ImmutableList<TypeToken<? super T>> boundsAsInterfaces(Type[] bounds) {
ImmutableList.Builder<TypeToken<? super T>> builder = ImmutableList.builder();
for (Type bound : bounds) {
@SuppressWarnings("unchecked") // upper bound of T
TypeToken<? super T> boundType = (TypeToken<? super T>) of(bound);
if (boundType.getRawType().isInterface()) {
builder.add(boundType);
}
}
return builder.build();
}
/**
* Returns the set of interfaces and classes that this type is or is a subtype of. The returned
* types are parameterized with proper type arguments.
*
* <p>Subtypes are always listed before supertypes. But the reverse is not true. A type isn't
* necessarily a subtype of all the types following. Order between types without subtype
* relationship is arbitrary and not guaranteed.
*
* <p>If this type is a type variable or wildcard, upper bounds that are themselves type variables
* aren't included (their super interfaces and superclasses are).
*/
public final TypeSet getTypes() {
return new TypeSet();
}
/**
* Returns the generic form of {@code superclass}. For example, if this is {@code
* ArrayList<String>}, {@code Iterable<String>} is returned given the input {@code
* Iterable.class}.
*/
public final TypeToken<? super T> getSupertype(Class<? super T> superclass) {
checkArgument(
this.someRawTypeIsSubclassOf(superclass),
"%s is not a super class of %s",
superclass,
this);
if (runtimeType instanceof TypeVariable) {
return getSupertypeFromUpperBounds(superclass, ((TypeVariable<?>) runtimeType).getBounds());
}
if (runtimeType instanceof WildcardType) {
return getSupertypeFromUpperBounds(superclass, ((WildcardType) runtimeType).getUpperBounds());
}
if (superclass.isArray()) {
return getArraySupertype(superclass);
}
@SuppressWarnings("unchecked") // resolved supertype
TypeToken<? super T> supertype =
(TypeToken<? super T>) resolveSupertype(toGenericType(superclass).runtimeType);
return supertype;
}
/**
* Returns subtype of {@code this} with {@code subclass} as the raw class. For example, if this is
* {@code Iterable<String>} and {@code subclass} is {@code List}, {@code List<String>} is
* returned.
*/
public final TypeToken<? extends T> getSubtype(Class<?> subclass) {
checkArgument(
!(runtimeType instanceof TypeVariable), "Cannot get subtype of type variable <%s>", this);
if (runtimeType instanceof WildcardType) {
return getSubtypeFromLowerBounds(subclass, ((WildcardType) runtimeType).getLowerBounds());
}
// unwrap array type if necessary
if (isArray()) {
return getArraySubtype(subclass);
}
// At this point, it's either a raw class or parameterized type.
checkArgument(
getRawType().isAssignableFrom(subclass), "%s isn't a subclass of %s", subclass, this);
Type resolvedTypeArgs = resolveTypeArgsForSubclass(subclass);
@SuppressWarnings("unchecked") // guarded by the isAssignableFrom() statement above
TypeToken<? extends T> subtype = (TypeToken<? extends T>) of(resolvedTypeArgs);
checkArgument(
subtype.isSubtypeOf(this), "%s does not appear to be a subtype of %s", subtype, this);
return subtype;
}
/**
* Returns true if this type is a supertype of the given {@code type}. "Supertype" is defined
* according to <a
* href="http://docs.oracle.com/javase/specs/jls/se8/html/jls-4.html#jls-4.5.1">the rules for type
* arguments</a> introduced with Java generics.
*
* @since 19.0
*/
public final boolean isSupertypeOf(TypeToken<?> type) {
return type.isSubtypeOf(getType());
}
/**
* Returns true if this type is a supertype of the given {@code type}. "Supertype" is defined
* according to <a
* href="http://docs.oracle.com/javase/specs/jls/se8/html/jls-4.html#jls-4.5.1">the rules for type
* arguments</a> introduced with Java generics.
*
* @since 19.0
*/
public final boolean isSupertypeOf(Type type) {
return of(type).isSubtypeOf(getType());
}
/**
* Returns true if this type is a subtype of the given {@code type}. "Subtype" is defined
* according to <a
* href="http://docs.oracle.com/javase/specs/jls/se8/html/jls-4.html#jls-4.5.1">the rules for type
* arguments</a> introduced with Java generics.
*
* @since 19.0
*/
public final boolean isSubtypeOf(TypeToken<?> type) {
return isSubtypeOf(type.getType());
}
/**
* Returns true if this type is a subtype of the given {@code type}. "Subtype" is defined
* according to <a
* href="http://docs.oracle.com/javase/specs/jls/se8/html/jls-4.html#jls-4.5.1">the rules for type
* arguments</a> introduced with Java generics.
*
* @since 19.0
*/
public final boolean isSubtypeOf(Type supertype) {
checkNotNull(supertype);
if (supertype instanceof WildcardType) {
// if 'supertype' is <? super Foo>, 'this' can be:
// Foo, SubFoo, <? extends Foo>.
// if 'supertype' is <? extends Foo>, nothing is a subtype.
return any(((WildcardType) supertype).getLowerBounds()).isSupertypeOf(runtimeType);
}
// if 'this' is wildcard, it's a suptype of to 'supertype' if any of its "extends"
// bounds is a subtype of 'supertype'.
if (runtimeType instanceof WildcardType) {
// <? super Base> is of no use in checking 'from' being a subtype of 'to'.
return any(((WildcardType) runtimeType).getUpperBounds()).isSubtypeOf(supertype);
}
// if 'this' is type variable, it's a subtype if any of its "extends"
// bounds is a subtype of 'supertype'.
if (runtimeType instanceof TypeVariable) {
return runtimeType.equals(supertype)
|| any(((TypeVariable<?>) runtimeType).getBounds()).isSubtypeOf(supertype);
}
if (runtimeType instanceof GenericArrayType) {
return of(supertype).isSupertypeOfArray((GenericArrayType) runtimeType);
}
// Proceed to regular Type subtype check
if (supertype instanceof Class) {
return this.someRawTypeIsSubclassOf((Class<?>) supertype);
} else if (supertype instanceof ParameterizedType) {
return this.isSubtypeOfParameterizedType((ParameterizedType) supertype);
} else if (supertype instanceof GenericArrayType) {
return this.isSubtypeOfArrayType((GenericArrayType) supertype);
} else { // to instanceof TypeVariable
return false;
}
}
/**
* Returns true if this type is known to be an array type, such as {@code int[]}, {@code T[]},
* {@code <? extends Map<String, Integer>[]>} etc.
*/
public final boolean isArray() {
return getComponentType() != null;
}
/**
* Returns true if this type is one of the nine primitive types (including {@code void}).
*
* @since 15.0
*/
public final boolean isPrimitive() {
return (runtimeType instanceof Class) && ((Class<?>) runtimeType).isPrimitive();
}
/**
* Returns the corresponding wrapper type if this is a primitive type; otherwise returns {@code
* this} itself. Idempotent.
*
* @since 15.0
*/
public final TypeToken<T> wrap() {
if (isPrimitive()) {
@SuppressWarnings("unchecked") // this is a primitive class
Class<T> type = (Class<T>) runtimeType;
return of(Primitives.wrap(type));
}
return this;
}
private boolean isWrapper() {
return Primitives.allWrapperTypes().contains(runtimeType);
}
/**
* Returns the corresponding primitive type if this is a wrapper type; otherwise returns {@code
* this} itself. Idempotent.
*
* @since 15.0
*/
public final TypeToken<T> unwrap() {
if (isWrapper()) {
@SuppressWarnings("unchecked") // this is a wrapper class
Class<T> type = (Class<T>) runtimeType;
return of(Primitives.unwrap(type));
}
return this;
}
/**
* Returns the array component type if this type represents an array ({@code int[]}, {@code T[]},
* {@code <? extends Map<String, Integer>[]>} etc.), or else {@code null} is returned.
*/
@NullableDecl
public final TypeToken<?> getComponentType() {
Type componentType = Types.getComponentType(runtimeType);
if (componentType == null) {
return null;
}
return of(componentType);
}
/**
* Returns the {@link Invokable} for {@code method}, which must be a member of {@code T}.
*
* @since 14.0
*/
public final Invokable<T, Object> method(Method method) {
checkArgument(
this.someRawTypeIsSubclassOf(method.getDeclaringClass()),
"%s not declared by %s",
method,
this);
return new Invokable.MethodInvokable<T>(method) {
@Override
Type getGenericReturnType() {
return getCovariantTypeResolver().resolveType(super.getGenericReturnType());
}
@Override
Type[] getGenericParameterTypes() {
return getInvariantTypeResolver().resolveTypesInPlace(super.getGenericParameterTypes());
}
@Override
Type[] getGenericExceptionTypes() {
return getCovariantTypeResolver().resolveTypesInPlace(super.getGenericExceptionTypes());
}
@Override
public TypeToken<T> getOwnerType() {
return TypeToken.this;
}
@Override
public String toString() {
return getOwnerType() + "." + super.toString();
}
};
}
/**
* Returns the {@link Invokable} for {@code constructor}, which must be a member of {@code T}.
*
* @since 14.0
*/
public final Invokable<T, T> constructor(Constructor<?> constructor) {
checkArgument(
constructor.getDeclaringClass() == getRawType(),
"%s not declared by %s",
constructor,
getRawType());
return new Invokable.ConstructorInvokable<T>(constructor) {
@Override
Type getGenericReturnType() {
return getCovariantTypeResolver().resolveType(super.getGenericReturnType());
}
@Override
Type[] getGenericParameterTypes() {
return getInvariantTypeResolver().resolveTypesInPlace(super.getGenericParameterTypes());
}
@Override
Type[] getGenericExceptionTypes() {
return getCovariantTypeResolver().resolveTypesInPlace(super.getGenericExceptionTypes());
}
@Override
public TypeToken<T> getOwnerType() {
return TypeToken.this;
}
@Override
public String toString() {
return getOwnerType() + "(" + Joiner.on(", ").join(getGenericParameterTypes()) + ")";
}
};
}
/**
* The set of interfaces and classes that {@code T} is or is a subtype of. {@link Object} is not
* included in the set if this type is an interface.
*
* @since 13.0
*/
public class TypeSet extends ForwardingSet<TypeToken<? super T>> implements Serializable {
@MonotonicNonNullDecl private transient ImmutableSet<TypeToken<? super T>> types;
TypeSet() {}
/** Returns the types that are interfaces implemented by this type. */
public TypeSet interfaces() {
return new InterfaceSet(this);
}
/** Returns the types that are classes. */
public TypeSet classes() {
return new ClassSet();
}
@Override
protected Set<TypeToken<? super T>> delegate() {
ImmutableSet<TypeToken<? super T>> filteredTypes = types;
if (filteredTypes == null) {
// Java has no way to express ? super T when we parameterize TypeToken vs. Class.
@SuppressWarnings({"unchecked", "rawtypes"})
ImmutableList<TypeToken<? super T>> collectedTypes =
(ImmutableList) TypeCollector.FOR_GENERIC_TYPE.collectTypes(TypeToken.this);
return (types =
FluentIterable.from(collectedTypes)
.filter(TypeFilter.IGNORE_TYPE_VARIABLE_OR_WILDCARD)
.toSet());
} else {
return filteredTypes;
}
}
/** Returns the raw types of the types in this set, in the same order. */
public Set<Class<? super T>> rawTypes() {
// Java has no way to express ? super T when we parameterize TypeToken vs. Class.
@SuppressWarnings({"unchecked", "rawtypes"})
ImmutableList<Class<? super T>> collectedTypes =
(ImmutableList) TypeCollector.FOR_RAW_TYPE.collectTypes(getRawTypes());
return ImmutableSet.copyOf(collectedTypes);
}
private static final long serialVersionUID = 0;
}
private final class InterfaceSet extends TypeSet {
private final transient TypeSet allTypes;
@MonotonicNonNullDecl private transient ImmutableSet<TypeToken<? super T>> interfaces;
InterfaceSet(TypeSet allTypes) {
this.allTypes = allTypes;
}
@Override
protected Set<TypeToken<? super T>> delegate() {
ImmutableSet<TypeToken<? super T>> result = interfaces;
if (result == null) {
return (interfaces =
FluentIterable.from(allTypes).filter(TypeFilter.INTERFACE_ONLY).toSet());
} else {
return result;
}
}
@Override
public TypeSet interfaces() {
return this;
}
@Override
public Set<Class<? super T>> rawTypes() {
// Java has no way to express ? super T when we parameterize TypeToken vs. Class.
@SuppressWarnings({"unchecked", "rawtypes"})
ImmutableList<Class<? super T>> collectedTypes =
(ImmutableList) TypeCollector.FOR_RAW_TYPE.collectTypes(getRawTypes());
return FluentIterable.from(collectedTypes)
.filter(
new Predicate<Class<?>>() {
@Override
public boolean apply(Class<?> type) {
return type.isInterface();
}
})
.toSet();
}
@Override
public TypeSet classes() {
throw new UnsupportedOperationException("interfaces().classes() not supported.");
}
private Object readResolve() {
return getTypes().interfaces();
}
private static final long serialVersionUID = 0;
}
private final class ClassSet extends TypeSet {
@MonotonicNonNullDecl private transient ImmutableSet<TypeToken<? super T>> classes;
@Override
protected Set<TypeToken<? super T>> delegate() {
ImmutableSet<TypeToken<? super T>> result = classes;
if (result == null) {
@SuppressWarnings({"unchecked", "rawtypes"})
ImmutableList<TypeToken<? super T>> collectedTypes =
(ImmutableList)
TypeCollector.FOR_GENERIC_TYPE.classesOnly().collectTypes(TypeToken.this);
return (classes =
FluentIterable.from(collectedTypes)
.filter(TypeFilter.IGNORE_TYPE_VARIABLE_OR_WILDCARD)
.toSet());
} else {
return result;
}
}
@Override
public TypeSet classes() {
return this;
}
@Override
public Set<Class<? super T>> rawTypes() {
// Java has no way to express ? super T when we parameterize TypeToken vs. Class.
@SuppressWarnings({"unchecked", "rawtypes"})
ImmutableList<Class<? super T>> collectedTypes =
(ImmutableList) TypeCollector.FOR_RAW_TYPE.classesOnly().collectTypes(getRawTypes());
return ImmutableSet.copyOf(collectedTypes);
}
@Override
public TypeSet interfaces() {
throw new UnsupportedOperationException("classes().interfaces() not supported.");
}
private Object readResolve() {
return getTypes().classes();
}
private static final long serialVersionUID = 0;
}
private enum TypeFilter implements Predicate<TypeToken<?>> {
IGNORE_TYPE_VARIABLE_OR_WILDCARD {
@Override
public boolean apply(TypeToken<?> type) {
return !(type.runtimeType instanceof TypeVariable
|| type.runtimeType instanceof WildcardType);
}
},
INTERFACE_ONLY {
@Override
public boolean apply(TypeToken<?> type) {
return type.getRawType().isInterface();
}
}
}
/**
* Returns true if {@code o} is another {@code TypeToken} that represents the same {@link Type}.
*/
@Override
public boolean equals(@NullableDecl Object o) {
if (o instanceof TypeToken) {
TypeToken<?> that = (TypeToken<?>) o;
return runtimeType.equals(that.runtimeType);
}
return false;
}
@Override
public int hashCode() {
return runtimeType.hashCode();
}
@Override
public String toString() {
return Types.toString(runtimeType);
}
/** Implemented to support serialization of subclasses. */
protected Object writeReplace() {
// TypeResolver just transforms the type to our own impls that are Serializable
// except TypeVariable.
return of(new TypeResolver().resolveType(runtimeType));
}
/**
* Ensures that this type token doesn't contain type variables, which can cause unchecked type
* errors for callers like {@link TypeToInstanceMap}.
*/
@CanIgnoreReturnValue
final TypeToken<T> rejectTypeVariables() {
new TypeVisitor() {
@Override
void visitTypeVariable(TypeVariable<?> type) {
throw new IllegalArgumentException(
runtimeType + "contains a type variable and is not safe for the operation");
}
@Override
void visitWildcardType(WildcardType type) {
visit(type.getLowerBounds());
visit(type.getUpperBounds());
}
@Override
void visitParameterizedType(ParameterizedType type) {
visit(type.getActualTypeArguments());
visit(type.getOwnerType());
}
@Override
void visitGenericArrayType(GenericArrayType type) {
visit(type.getGenericComponentType());
}
}.visit(runtimeType);
return this;
}
private boolean someRawTypeIsSubclassOf(Class<?> superclass) {
for (Class<?> rawType : getRawTypes()) {
if (superclass.isAssignableFrom(rawType)) {
return true;
}
}
return false;
}
private boolean isSubtypeOfParameterizedType(ParameterizedType supertype) {
Class<?> matchedClass = of(supertype).getRawType();
if (!someRawTypeIsSubclassOf(matchedClass)) {
return false;
}
TypeVariable<?>[] typeVars = matchedClass.getTypeParameters();
Type[] supertypeArgs = supertype.getActualTypeArguments();
for (int i = 0; i < typeVars.length; i++) {
Type subtypeParam = getCovariantTypeResolver().resolveType(typeVars[i]);
// If 'supertype' is "List<? extends CharSequence>"
// and 'this' is StringArrayList,
// First step is to figure out StringArrayList "is-a" List<E> where <E> = String.
// String is then matched against <? extends CharSequence>, the supertypeArgs[0].
if (!of(subtypeParam).is(supertypeArgs[i], typeVars[i])) {
return false;
}
}
// We only care about the case when the supertype is a non-static inner class
// in which case we need to make sure the subclass's owner type is a subtype of the
// supertype's owner.
return Modifier.isStatic(((Class<?>) supertype.getRawType()).getModifiers())
|| supertype.getOwnerType() == null
|| isOwnedBySubtypeOf(supertype.getOwnerType());
}
private boolean isSubtypeOfArrayType(GenericArrayType supertype) {
if (runtimeType instanceof Class) {
Class<?> fromClass = (Class<?>) runtimeType;
if (!fromClass.isArray()) {
return false;
}
return of(fromClass.getComponentType()).isSubtypeOf(supertype.getGenericComponentType());
} else if (runtimeType instanceof GenericArrayType) {
GenericArrayType fromArrayType = (GenericArrayType) runtimeType;
return of(fromArrayType.getGenericComponentType())
.isSubtypeOf(supertype.getGenericComponentType());
} else {
return false;
}
}
private boolean isSupertypeOfArray(GenericArrayType subtype) {
if (runtimeType instanceof Class) {
Class<?> thisClass = (Class<?>) runtimeType;
if (!thisClass.isArray()) {
return thisClass.isAssignableFrom(Object[].class);
}
return of(subtype.getGenericComponentType()).isSubtypeOf(thisClass.getComponentType());
} else if (runtimeType instanceof GenericArrayType) {
return of(subtype.getGenericComponentType())
.isSubtypeOf(((GenericArrayType) runtimeType).getGenericComponentType());
} else {
return false;
}
}
/**
* {@code A.is(B)} is defined as {@code Foo<A>.isSubtypeOf(Foo<B>)}.
*
* <p>Specifically, returns true if any of the following conditions is met:
* <ol>
* <li>'this' and {@code formalType} are equal.
* <li>'this' and {@code formalType} have equal canonical form.
* <li>{@code formalType} is {@code <? extends Foo>} and 'this' is a subtype of {@code Foo}.
* <li>{@code formalType} is {@code <? super Foo>} and 'this' is a supertype of {@code Foo}.
* </ol>
* Note that condition 2 isn't technically accurate under the context of a recursively
* bounded type variables. For example, {@code Enum<? extends Enum<E>>} canonicalizes to
* {@code Enum<?>} where {@code E} is the type variable declared on the {@code Enum} class
* declaration. It's technically <em>not</em> true that {@code Foo<Enum<? extends Enum<E>>>} is a
* subtype of {@code Foo<Enum<?>>} according to JLS. See testRecursiveWildcardSubtypeBug() for
* a real example.
*
* <p>It appears that properly handling recursive type bounds in the presence of implicit type
* bounds is not easy. For now we punt, hoping that this defect should rarely cause issues in real
* code.
*
* @param formalType is {@code Foo<formalType>} a supertype of {@code Foo<T>}?
* @param declaration The type variable in the context of a parameterized type. Used to infer
* type bound when {@code formalType} is a wildcard with implicit upper bound.
*/
private boolean is(Type formalType, TypeVariable<?> declaration) {
if (runtimeType.equals(formalType)) {
return true;
}
if (formalType instanceof WildcardType) {
WildcardType your = canonicalizeWildcardType(declaration, (WildcardType) formalType);
// if "formalType" is <? extends Foo>, "this" can be:
// Foo, SubFoo, <? extends Foo>, <? extends SubFoo>, <T extends Foo> or
// <T extends SubFoo>.
// if "formalType" is <? super Foo>, "this" can be:
// Foo, SuperFoo, <? super Foo> or <? super SuperFoo>.
return every(your.getUpperBounds()).isSupertypeOf(runtimeType)
&& every(your.getLowerBounds()).isSubtypeOf(runtimeType);
}
return canonicalizeWildcardsInType(runtimeType)
.equals(canonicalizeWildcardsInType(formalType));
}
/**
* In reflection, {@code Foo<?>.getUpperBounds()[0]} is always {@code Object.class}, even when Foo
* is defined as {@code Foo<T extends String>}. Thus directly calling {@code <?>.is(String.class)}
* will return false. To mitigate, we canonicalize wildcards by enforcing the following
* invariants:
* <ol>
* <li>{@code canonicalize(t)} always produces the equal result for equivalent types. For example
* both {@code Enum<?>} and {@code Enum<? extends Enum<?>>} canonicalize to
* {@code Enum<? extends Enum<E>}.
* <li>{@code canonicalize(t)} produces a "literal" supertype of t.
* For example: {@code Enum<? extends Enum<?>>} canonicalizes to {@code Enum<?>}, which is
* a supertype (if we disregard the upper bound is implicitly an Enum too).