-
-
Notifications
You must be signed in to change notification settings - Fork 1.4k
/
TypeFactory.java
1591 lines (1464 loc) · 64.9 KB
/
TypeFactory.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
package tools.jackson.databind.type;
import java.util.*;
import java.util.concurrent.atomic.AtomicReference;
import java.util.stream.BaseStream;
import java.util.stream.DoubleStream;
import java.util.stream.IntStream;
import java.util.stream.LongStream;
import java.util.stream.Stream;
import java.lang.reflect.*;
import tools.jackson.core.type.TypeReference;
import tools.jackson.core.util.Snapshottable;
import tools.jackson.databind.*;
import tools.jackson.databind.util.*;
/**
* Class used for creating concrete {@link JavaType} instances,
* given various inputs.
*<p>
* Instances of this class are accessible using {@link tools.jackson.databind.ObjectMapper}
* as well as many objects it constructs (like
* {@link tools.jackson.databind.DeserializationConfig} and
* {@link tools.jackson.databind.SerializationConfig})),
* but usually those objects also
* expose convenience methods (<code>constructType</code>).
* So, you can do for example:
*<pre>
* JavaType stringType = mapper.constructType(String.class);
*</pre>
* However, more advanced methods are only exposed by factory so that you
* may need to use:
*<pre>
* JavaType stringCollection = mapper.getTypeFactory().constructCollectionType(List.class, String.class);
*</pre>
*<p>
* Note on optimizations: generic type parameters are resolved for all types, with following
* exceptions:
*<ul>
* <li>For optimization purposes, type resolution is skipped for following commonly seen
* types that do have type parameters, but ones that are rarely needed:
* <ul>
* <li>{@link java.lang.Enum}: Self-referential type reference is simply dropped and
* Class is exposed as a simple, non-parameterized {@link SimpleType}
* </li>
* <li>{@link java.lang.Comparable}: Type parameter is simply dropped and and
* interface is exposed as a simple, non-parameterized {@link SimpleType}
* </li>
* <li>Up until Jackson 2.13, {@link java.lang.Class} type parameter was dropped; resolution
* was added back in Jackson 2.14.
* </li>
* </ul>
* </li>
* <li>For {@link java.util.Collection} subtypes, resolved type is ALWAYS the parameter for
* {link java.util.Collection} and not that of actually resolved subtype.
* This is usually (but not always) same parameter.
* </li>
* <li>For {@link java.util.Map} subtypes, resolved type is ALWAYS the parameter for
* {link java.util.Map} and not that of actually resolved subtype.
* These are usually (but not always) same parameters.
* </li>
*</ul>
*/
@SuppressWarnings({"rawtypes" })
public final class TypeFactory
implements Snapshottable<TypeFactory>,
java.io.Serializable
{
private static final long serialVersionUID = 3L;
/**
* Default size used to construct {@link #_typeCache}.
*/
public static final int DEFAULT_MAX_CACHE_SIZE = 200;
private final static JavaType[] NO_TYPES = new JavaType[0];
/**
* Globally shared singleton. Not accessed directly; non-core
* code should use per-ObjectMapper instance (via configuration objects).
* Core Jackson code uses {@link #defaultInstance} for accessing it.
*/
protected final static TypeFactory instance = new TypeFactory();
protected final static TypeBindings EMPTY_BINDINGS = TypeBindings.emptyBindings();
/*
/**********************************************************************
/* Constants for "well-known" classes
/**********************************************************************
*/
// // // Let's assume that a small set of core primitive/basic types
// // // will not be modified, and can be freely shared to streamline
// // // parts of processing
private final static Class<?> CLS_STRING = String.class;
private final static Class<?> CLS_OBJECT = Object.class;
private final static Class<?> CLS_COMPARABLE = Comparable.class;
private final static Class<?> CLS_ENUM = Enum.class;
private final static Class<?> CLS_JSON_NODE = JsonNode.class;
private final static Class<?> CLS_BOOL = Boolean.TYPE;
private final static Class<?> CLS_DOUBLE = Double.TYPE;
private final static Class<?> CLS_INT = Integer.TYPE;
private final static Class<?> CLS_LONG = Long.TYPE;
/*
/**********************************************************************
/* Cached pre-constructed JavaType instances
/**********************************************************************
*/
// note: these are primitive, hence no super types
protected final static SimpleType CORE_TYPE_BOOL = new SimpleType(CLS_BOOL);
protected final static SimpleType CORE_TYPE_DOUBLE = new SimpleType(CLS_DOUBLE);
protected final static SimpleType CORE_TYPE_INT = new SimpleType(CLS_INT);
protected final static SimpleType CORE_TYPE_LONG = new SimpleType(CLS_LONG);
// and as to String... well, for now, ignore its super types
protected final static SimpleType CORE_TYPE_STRING = new SimpleType(CLS_STRING);
protected final static SimpleType CORE_TYPE_OBJECT = new SimpleType(CLS_OBJECT);
/**
* Cache {@link Comparable} because it is both parametric (relatively costly to
* resolve) and mostly useless (no special handling), better handle directly
*/
protected final static SimpleType CORE_TYPE_COMPARABLE = new SimpleType(CLS_COMPARABLE);
/**
* Cache {@link Enum} because it is parametric AND self-referential (costly to
* resolve) and useless in itself (no special handling).
*/
protected final static SimpleType CORE_TYPE_ENUM = new SimpleType(CLS_ENUM);
/**
* Cache {@link JsonNode} because it is no critical path of simple tree model
* reading and does not have things to override
*/
protected final static SimpleType CORE_TYPE_JSON_NODE = new SimpleType(CLS_JSON_NODE);
/**
* Since type resolution can be expensive (specifically when resolving
* actual generic types), we will use small cache to avoid repetitive
* resolution of core types
*/
protected final LookupCache<Object,JavaType> _typeCache;
/*
/**********************************************************************
/* Configuration
/**********************************************************************
*/
/**
* Registered {@link TypeModifier}s: objects that can change details
* of {@link JavaType} instances factory constructs.
*/
protected final TypeModifier[] _modifiers;
/**
* ClassLoader used by this factory [databind#624].
*/
protected final ClassLoader _classLoader;
/*
/**********************************************************************
/* Life-cycle
/**********************************************************************
*/
private TypeFactory() {
this(new SimpleLookupCache<Object,JavaType>(16, DEFAULT_MAX_CACHE_SIZE));
}
protected TypeFactory(LookupCache<Object,JavaType> typeCache) {
this(typeCache, null, null);
}
protected TypeFactory(LookupCache<Object,JavaType> typeCache,
TypeModifier[] mods, ClassLoader classLoader)
{
_typeCache = Objects.requireNonNull(typeCache);
_modifiers = mods;
_classLoader = classLoader;
}
/**
* Need to make a copy on snapshot() to avoid accidental leakage via cache.
* In theory only needed if there are modifiers, but since these are lightweight
* objects, let's recreate always.
*/
@Override
public TypeFactory snapshot() {
return new TypeFactory(_typeCache.snapshot(),
// this is safe since array never modified, always copy-on-mod
_modifiers,
_classLoader);
}
/**
* "Mutant factory" method which will construct a new instance with specified
* {@link TypeModifier} added as the first modifier to call (in case there
* are multiple registered).
*/
public TypeFactory withModifier(TypeModifier mod)
{
LookupCache<Object,JavaType> typeCache = _typeCache;
TypeModifier[] mods;
if (mod == null) { // mostly for unit tests
mods = null;
// 30-Jun-2016, tatu: for some reason expected semantics are to clear cache
// in this case; can't recall why, but keeping the same
typeCache = typeCache.emptyCopy();
} else if (_modifiers == null) {
mods = new TypeModifier[] { mod };
// 29-Jul-2019, tatu: Actually I think we better clear cache in this case
// as well to ensure no leakage occurs (see [databind#2395])
typeCache = typeCache.emptyCopy();
} else {
// but may keep existing cache otherwise
mods = ArrayBuilders.insertInListNoDup(_modifiers, mod);
}
return new TypeFactory(typeCache, mods, _classLoader);
}
/**
* "Mutant factory" method which will construct a new instance with specified
* {@link ClassLoader} to use by {@link #findClass}.
*/
public TypeFactory withClassLoader(ClassLoader classLoader) {
return new TypeFactory(_typeCache, _modifiers, classLoader);
}
/**
* Mutant factory method that will construct new {@link TypeFactory} with
* identical settings except for different cache.
*/
public TypeFactory withCache(LookupCache<Object,JavaType> cache) {
return new TypeFactory(cache, _modifiers, _classLoader);
}
/**
* Method used to access the globally shared instance, which has
* no custom configuration. Used by <code>ObjectMapper</code> to
* get the default factory when constructed.
*/
public static TypeFactory defaultInstance() { return instance; }
/**
* Method that will clear up any cached type definitions that may
* be cached by this {@link TypeFactory} instance.
* This method should not be commonly used, that is, only use it
* if you know there is a problem with retention of type definitions;
* the most likely (and currently only known) problem is retention
* of {@link Class} instances via {@link JavaType} reference.
*/
public void clearCache() {
_typeCache.clear();
}
public ClassLoader getClassLoader() {
return _classLoader;
}
/*
/**********************************************************************
/* Static methods for non-instance-specific functionality
/**********************************************************************
*/
/**
* Method for constructing a marker type that indicates missing generic
* type information, which is handled same as simple type for
* <code>java.lang.Object</code>.
*/
public static JavaType unknownType() {
return defaultInstance()._unknownType();
}
/**
* Static helper method that can be called to figure out type-erased
* call for given JDK type. It can be called statically since type resolution
* process can never change actual type-erased class; thereby static
* default instance is used for determination.
*/
public static Class<?> rawClass(Type t) {
if (t instanceof Class<?>) {
return (Class<?>) t;
} else if (t instanceof JavaType) {
return ((JavaType) t).getRawClass();
} else if (t instanceof GenericArrayType) {
return Array.newInstance(rawClass(((GenericArrayType) t).getGenericComponentType()), 0).getClass();
} else if (t instanceof ParameterizedType) {
return rawClass(((ParameterizedType) t).getRawType());
} else if (t instanceof TypeVariable<?>) {
return rawClass(((TypeVariable<?>) t).getBounds()[0]);
} else if (t instanceof WildcardType) {
return rawClass(((WildcardType) t).getUpperBounds()[0]);
}
// fallback
return defaultInstance().constructType(t).getRawClass();
}
/*
/**********************************************************************
/* Low-level helper methods
/**********************************************************************
*/
/**
* Low-level lookup method moved from {@link tools.jackson.databind.util.ClassUtil},
* to allow for overriding of lookup functionality in environments like OSGi.
*/
public Class<?> findClass(String className) throws ClassNotFoundException
{
if (className.indexOf('.') < 0) {
Class<?> prim = _findPrimitive(className);
if (prim != null) {
return prim;
}
}
// Two-phase lookup: first using context ClassLoader; then default
Throwable prob = null;
ClassLoader loader = this.getClassLoader();
if (loader == null) {
loader = Thread.currentThread().getContextClassLoader();
}
if (loader != null) {
try {
return classForName(className, true, loader);
} catch (Exception e) {
prob = ClassUtil.getRootCause(e);
}
}
try {
return classForName(className);
} catch (Exception e) {
if (prob == null) {
prob = ClassUtil.getRootCause(e);
}
}
ClassUtil.throwIfRTE(prob);
throw new ClassNotFoundException(prob.getMessage(), prob);
}
protected Class<?> classForName(String name, boolean initialize,
ClassLoader loader) throws ClassNotFoundException {
return Class.forName(name, true, loader);
}
protected Class<?> classForName(String name) throws ClassNotFoundException {
return Class.forName(name);
}
protected Class<?> _findPrimitive(String className)
{
if ("int".equals(className)) return Integer.TYPE;
if ("long".equals(className)) return Long.TYPE;
if ("float".equals(className)) return Float.TYPE;
if ("double".equals(className)) return Double.TYPE;
if ("boolean".equals(className)) return Boolean.TYPE;
if ("byte".equals(className)) return Byte.TYPE;
if ("char".equals(className)) return Character.TYPE;
if ("short".equals(className)) return Short.TYPE;
if ("void".equals(className)) return Void.TYPE;
return null;
}
/*
/**********************************************************************
/* Type conversion, parameterization resolution methods
/**********************************************************************
*/
/**
* Factory method for creating a subtype of given base type, as defined
* by specified subclass; but retaining generic type information if any.
* Can be used, for example, to get equivalent of "HashMap<String,Integer>"
* from "Map<String,Integer>" by giving <code>HashMap.class</code>
* as subclass.
* Short-cut for:
*<pre>
* constructSpecializedType(baseType, subclass, class);
*</pre>
* that is, will use "strict" compatibility checking, usually used for
* deserialization purposes (but often not for serialization).
*/
public JavaType constructSpecializedType(JavaType baseType, Class<?> subclass)
throws IllegalArgumentException
{
return constructSpecializedType(baseType, subclass, false);
}
/**
* Factory method for creating a subtype of given base type, as defined
* by specified subclass; but retaining generic type information if any.
* Can be used, for example, to get equivalent of "HashMap<String,Integer>"
* from "Map<String,Integer>" by giving <code>HashMap.class</code>
* as subclass.
*
* @param baseType Declared base type with resolved type parameters
* @param subclass Runtime subtype to use for resolving
* @param relaxedCompatibilityCheck Whether checking for type-assignment compatibility
* should be "relaxed" ({@code true}) or "strict" ({@code false}): typically
* serialization uses relaxed, deserialization strict checking.
*
* @return Resolved sub-type
*/
public JavaType constructSpecializedType(JavaType baseType, Class<?> subclass,
boolean relaxedCompatibilityCheck)
throws IllegalArgumentException
{
// simple optimization to avoid costly introspection if type-erased type does NOT differ
final Class<?> rawBase = baseType.getRawClass();
if (rawBase == subclass) {
return baseType;
}
JavaType newType;
// also: if we start from untyped, not much to save
do { // bogus loop to be able to break
if (rawBase == Object.class) {
newType = _fromClass(null, subclass, EMPTY_BINDINGS);
break;
}
if (!rawBase.isAssignableFrom(subclass)) {
throw new IllegalArgumentException(String.format("Class %s not subtype of %s",
ClassUtil.nameOf(subclass), ClassUtil.getTypeDescription(baseType)
));
}
// A few special cases where we can simplify handling:
// (1) A small set of "well-known" List/Map subtypes where can take a short-cut
if (baseType.isContainerType()) {
if (baseType.isMapLikeType()) {
if ((subclass == HashMap.class)
|| (subclass == LinkedHashMap.class)
|| (subclass == EnumMap.class)
|| (subclass == TreeMap.class)) {
newType = _fromClass(null, subclass,
TypeBindings.create(subclass, baseType.getKeyType(), baseType.getContentType()));
break;
}
} else if (baseType.isCollectionLikeType()) {
if ((subclass == ArrayList.class)
|| (subclass == LinkedList.class)
|| (subclass == HashSet.class)
|| (subclass == TreeSet.class)) {
newType = _fromClass(null, subclass,
TypeBindings.create(subclass, baseType.getContentType()));
break;
}
// 29-Oct-2015, tatu: One further shortcut: there are variants of `EnumSet`,
// but they are impl details and we basically do not care...
if (rawBase == EnumSet.class) {
return baseType;
}
}
}
// (2) Original target type has no generics -- just resolve subtype
if (baseType.getBindings().isEmpty()) {
newType = _fromClass(null, subclass, EMPTY_BINDINGS);
break;
}
// (3) Sub-class does not take type parameters -- just resolve subtype
int typeParamCount = subclass.getTypeParameters().length;
if (typeParamCount == 0) {
newType = _fromClass(null, subclass, EMPTY_BINDINGS);
break;
}
// (4) If all else fails, do the full traversal using placeholders
TypeBindings tb = _bindingsForSubtype(baseType, typeParamCount,
subclass, relaxedCompatibilityCheck);
newType = _fromClass(null, subclass, tb);
} while (false);
// 25-Sep-2016, tatu: As per [databind#1384] also need to ensure handlers get
// copied as well
newType = newType.withHandlersFrom(baseType);
return newType;
}
private TypeBindings _bindingsForSubtype(JavaType baseType, int typeParamCount,
Class<?> subclass, boolean relaxedCompatibilityCheck)
{
PlaceholderForType[] placeholders = new PlaceholderForType[typeParamCount];
for (int i = 0; i < typeParamCount; ++i) {
placeholders[i] = new PlaceholderForType(i);
}
TypeBindings b = TypeBindings.create(subclass, placeholders);
// First: pseudo-resolve to get placeholders in place:
JavaType tmpSub = _fromClass(null, subclass, b);
// Then find super-type
JavaType baseWithPlaceholders = tmpSub.findSuperType(baseType.getRawClass());
if (baseWithPlaceholders == null) { // should be found but...
throw new IllegalArgumentException(String.format(
"Internal error: unable to locate supertype (%s) from resolved subtype %s", baseType.getRawClass().getName(),
subclass.getName()));
}
// and traverse type hierarchies to both verify and to resolve placeholders
String error = _resolveTypePlaceholders(baseType, baseWithPlaceholders);
if (error != null) {
// 28-Mar-2020, tatu: As per [databind#2632], need to ignore the issue in
// some cases. For now, just fully ignore; may need to refine in future
if (!relaxedCompatibilityCheck) {
throw new IllegalArgumentException("Failed to specialize base type "+baseType.toCanonical()+" as "
+subclass.getName()+", problem: "+error);
}
}
final JavaType[] typeParams = new JavaType[typeParamCount];
for (int i = 0; i < typeParamCount; ++i) {
JavaType t = placeholders[i].actualType();
// 18-Oct-2017, tatu: Looks like sometimes we have incomplete bindings (even if not
// common, it is possible if subtype is type-erased class with added type
// variable -- see test(s) with "bogus" type(s)).
if (t == null) {
t = unknownType();
}
typeParams[i] = t;
}
return TypeBindings.create(subclass, typeParams);
}
private String _resolveTypePlaceholders(JavaType sourceType, JavaType actualType)
throws IllegalArgumentException
{
List<JavaType> expectedTypes = sourceType.getBindings().getTypeParameters();
List<JavaType> actualTypes = actualType.getBindings().getTypeParameters();
final int actCount = actualTypes.size();
for (int i = 0, expCount = expectedTypes.size(); i < expCount; ++i) {
JavaType exp = expectedTypes.get(i);
JavaType act = (i < actCount) ? actualTypes.get(i) : unknownType();
if (!_verifyAndResolvePlaceholders(exp, act)) {
// 14-May-2018, tatu: As per [databind#2034] it seems we better relax assignment
// rules further -- at least likely "raw" (untyped, non-generic) base should probably
// allow specialization.
if (exp.hasRawClass(Object.class)) {
continue;
}
// 19-Apr-2018, tatu: Hack for [databind#1964] -- allow type demotion
// for `java.util.Map` key type if (and only if) target type is
// `java.lang.Object`
// 19-Aug-2019, tatu: Further, allow for all Map-like types, with assumption
// first argument would be key; initially just because Scala Maps have
// some issues (see [databind#2422])
if (i == 0) {
if (sourceType.isMapLikeType()
&& act.hasRawClass(Object.class)) {
continue;
}
}
// 19-Nov-2018, tatu: To solve [databind#2155], let's allow type-compatible
// assignment for interfaces at least...
if (exp.isInterface()) {
if (exp.isTypeOrSuperTypeOf(act.getRawClass())) {
continue;
}
}
return String.format("Type parameter #%d/%d differs; can not specialize %s with %s",
(i+1), expCount, exp.toCanonical(), act.toCanonical());
}
}
return null;
}
private boolean _verifyAndResolvePlaceholders(JavaType exp, JavaType act)
{
// See if we have an actual type placeholder to resolve; if yes, replace
if (act instanceof PlaceholderForType) {
((PlaceholderForType) act).actualType(exp);
return true;
}
// if not, try to verify compatibility. But note that we can not
// use simple equality as we need to resolve recursively
if (exp.getRawClass() != act.getRawClass()) {
return false;
}
// But we can check type parameters "blindly"
List<JavaType> expectedTypes = exp.getBindings().getTypeParameters();
List<JavaType> actualTypes = act.getBindings().getTypeParameters();
for (int i = 0, len = expectedTypes.size(); i < len; ++i) {
JavaType exp2 = expectedTypes.get(i);
JavaType act2 = actualTypes.get(i);
if (!_verifyAndResolvePlaceholders(exp2, act2)) {
return false;
}
}
return true;
}
/**
* Method similar to {@link #constructSpecializedType}, but that creates a
* less-specific type of given type. Usually this is as simple as simply
* finding super-type with type erasure of <code>superClass</code>, but
* there may be need for some additional work-arounds.
*/
public JavaType constructGeneralizedType(JavaType baseType, Class<?> superClass)
{
// simple optimization to avoid costly introspection if type-erased type does NOT differ
final Class<?> rawBase = baseType.getRawClass();
if (rawBase == superClass) {
return baseType;
}
JavaType superType = baseType.findSuperType(superClass);
if (superType == null) {
// Most likely, caller did not verify sub/super-type relationship
if (!superClass.isAssignableFrom(rawBase)) {
throw new IllegalArgumentException(String.format(
"Class %s not a super-type of %s", superClass.getName(), baseType));
}
// 01-Nov-2015, tatu: Should never happen, but ch
throw new IllegalArgumentException(String.format(
"Internal error: class %s not included as super-type for %s",
superClass.getName(), baseType));
}
return superType;
}
/**
* Factory method for constructing a {@link JavaType} out of its canonical
* representation (see {@link JavaType#toCanonical()}).
*
* @param canonical Canonical string representation of a type
*
* @throws IllegalArgumentException If canonical representation is malformed,
* or class that type represents (including its generic parameters) is
* not found
*/
public JavaType constructFromCanonical(String canonical) throws IllegalArgumentException
{
return TypeParser.instance.parse(this, canonical);
}
/**
* Method that is to figure out actual type parameters that given
* class binds to generic types defined by given (generic)
* interface or class.
* This could mean, for example, trying to figure out
* key and value types for Map implementations.
*
* @param type Sub-type (leaf type) that implements <code>expType</code>
*/
public JavaType[] findTypeParameters(JavaType type, Class<?> expType)
{
JavaType match = type.findSuperType(expType);
if (match == null) {
return NO_TYPES;
}
return match.getBindings().typeParameterArray();
}
/**
* Specialized alternative to {@link #findTypeParameters}
*
* @since 3.0
*/
public JavaType findFirstTypeParameter(JavaType type, Class<?> expType)
{
JavaType match = type.findSuperType(expType);
if (match != null) {
JavaType t = match.getBindings().getBoundTypeOrNull(0);
if (t != null) {
return t;
}
}
return _unknownType();
}
/**
* Method that can be called to figure out more specific of two
* types (if they are related; that is, one implements or extends the
* other); or if not related, return the primary type.
*
* @param type1 Primary type to consider
* @param type2 Secondary type to consider
*/
public JavaType moreSpecificType(JavaType type1, JavaType type2)
{
if (type1 == null) {
return type2;
}
if (type2 == null) {
return type1;
}
Class<?> raw1 = type1.getRawClass();
Class<?> raw2 = type2.getRawClass();
if (raw1 == raw2) {
return type1;
}
// TODO: maybe try sub-classing, to retain generic types?
if (raw1.isAssignableFrom(raw2)) {
return type2;
}
return type1;
}
/*
/**********************************************************************
/* Public general-purpose factory methods
/**********************************************************************
*/
public JavaType constructType(Type type) {
return _fromAny(null, type, EMPTY_BINDINGS);
}
public JavaType constructType(TypeReference<?> typeRef)
{
// 19-Oct-2015, tatu: Simpler variant like so should work
return _fromAny(null, typeRef.getType(), EMPTY_BINDINGS);
// but if not, due to funky sub-classing, type variables, what follows
// is a more complete processing a la Java ClassMate.
/*
final Class<?> refdRawType = typeRef.getClass();
JavaType type = _fromClass(null, refdRawType, EMPTY_BINDINGS);
JavaType genType = type.findSuperType(TypeReference.class);
if (genType == null) { // sanity check; shouldn't occur
throw new IllegalArgumentException("Unparameterized GenericType instance ("+refdRawType.getName()+")");
}
TypeBindings b = genType.getBindings();
JavaType[] params = b.typeParameterArray();
if (params.length == 0) {
throw new IllegalArgumentException("Unparameterized GenericType instance ("+refdRawType.getName()+")");
}
return params[0];
*/
}
/**
* Method to call when resolving types of {@link java.lang.reflect.Member}s
* like Fields, Methods and Constructor parameters and there is a
* {@link TypeBindings} (that describes binding of type parameters within
* context) to pass.
* This is typically used only by code in databind itself.
*
* @param type Type of a {@link java.lang.reflect.Member} to resolve
* @param contextBindings Type bindings from the context, often class in which
* member declared but may be subtype of that type (to bind actual bound
* type parametrers). Not used if {@code type} is of type {@code Class<?>}.
*
* @return Fully resolved type
*/
public JavaType resolveMemberType(Type type, TypeBindings contextBindings) {
return _fromAny(null, type, contextBindings);
}
// 20-Apr-2018, tatu: Really should get rid of this...
@Deprecated // since 2.8
public JavaType uncheckedSimpleType(Class<?> cls) {
// 18-Oct-2015, tatu: Not sure how much problem missing super-type info is here
return _constructSimple(cls, EMPTY_BINDINGS, null, null);
}
/*
/**********************************************************************
/* Direct factory methods
/**********************************************************************
*/
/**
* Method for constructing an {@link ArrayType}.
*<p>
* NOTE: type modifiers are NOT called on array type itself; but are called
* for element type (and other contained types)
*/
public ArrayType constructArrayType(Class<?> elementType) {
return ArrayType.construct(_fromAny(null, elementType, null), null);
}
/**
* Method for constructing an {@link ArrayType}.
*<p>
* NOTE: type modifiers are NOT called on array type itself; but are called
* for contained types.
*/
public ArrayType constructArrayType(JavaType elementType) {
return ArrayType.construct(elementType, null);
}
/**
* Method for constructing a {@link CollectionType}.
*<p>
* NOTE: type modifiers are NOT called on Collection type itself; but are called
* for contained types.
*/
public CollectionType constructCollectionType(Class<? extends Collection> collectionClass,
Class<?> elementClass) {
return constructCollectionType(collectionClass,
_fromClass(null, elementClass, EMPTY_BINDINGS));
}
/**
* Method for constructing a {@link CollectionType}.
*<p>
* NOTE: type modifiers are NOT called on Collection type itself; but are called
* for contained types.
*/
public CollectionType constructCollectionType(Class<? extends Collection> collectionClass,
JavaType elementType)
{
TypeBindings bindings = TypeBindings.createIfNeeded(collectionClass, elementType);
CollectionType result = (CollectionType) _fromClass(null, collectionClass, bindings);
// 17-May-2017, tatu: As per [databind#1415], we better verify bound values if (but only if)
// type being resolved was non-generic (i.e.element type was ignored)
if (bindings.isEmpty() && (elementType != null)) {
JavaType t = result.findSuperType(Collection.class);
JavaType realET = t.getContentType();
if (!realET.equals(elementType)) {
throw new IllegalArgumentException(String.format(
"Non-generic Collection class %s did not resolve to something with element type %s but %s ",
ClassUtil.nameOf(collectionClass), elementType, realET));
}
}
return result;
}
/**
* Method for constructing a {@link CollectionLikeType}.
*<p>
* NOTE: type modifiers are NOT called on constructed type itself; but are called
* for contained types.
*/
public CollectionLikeType constructCollectionLikeType(Class<?> collectionClass, Class<?> elementClass) {
return constructCollectionLikeType(collectionClass,
_fromClass(null, elementClass, EMPTY_BINDINGS));
}
/**
* Method for constructing a {@link CollectionLikeType}.
*<p>
* NOTE: type modifiers are NOT called on constructed type itself; but are called
* for contained types.
*/
public CollectionLikeType constructCollectionLikeType(Class<?> collectionClass, JavaType elementType) {
JavaType type = _fromClass(null, collectionClass,
TypeBindings.createIfNeeded(collectionClass, elementType));
if (type instanceof CollectionLikeType) {
return (CollectionLikeType) type;
}
return CollectionLikeType.upgradeFrom(type, elementType);
}
/**
* Method for constructing a {@link MapType} instance
*<p>
* NOTE: type modifiers are NOT called on constructed type itself; but are called
* for contained types.
*/
public MapType constructMapType(Class<? extends Map> mapClass,
Class<?> keyClass, Class<?> valueClass) {
JavaType kt, vt;
if (mapClass == Properties.class) {
kt = vt = CORE_TYPE_STRING;
} else {
kt = _fromClass(null, keyClass, EMPTY_BINDINGS);
vt = _fromClass(null, valueClass, EMPTY_BINDINGS);
}
return constructMapType(mapClass, kt, vt);
}
/**
* Method for constructing a {@link MapType} instance
*<p>
* NOTE: type modifiers are NOT called on constructed type itself.
*/
public MapType constructMapType(Class<? extends Map> mapClass, JavaType keyType, JavaType valueType) {
TypeBindings bindings = TypeBindings.createIfNeeded(mapClass, new JavaType[] { keyType, valueType });
MapType result = (MapType) _fromClass(null, mapClass, bindings);
// 17-May-2017, tatu: As per [databind#1415], we better verify bound values if (but only if)
// type being resolved was non-generic (i.e.element type was ignored)
if (bindings.isEmpty()) {
JavaType t = result.findSuperType(Map.class);
JavaType realKT = t.getKeyType();
if (!realKT.equals(keyType)) {
throw new IllegalArgumentException(String.format(
"Non-generic Map class %s did not resolve to something with key type %s but %s ",
ClassUtil.nameOf(mapClass), keyType, realKT));
}
JavaType realVT = t.getContentType();
if (!realVT.equals(valueType)) {
throw new IllegalArgumentException(String.format(
"Non-generic Map class %s did not resolve to something with value type %s but %s ",
ClassUtil.nameOf(mapClass), valueType, realVT));
}
}
return result;
}
/**
* Method for constructing a {@link MapLikeType} instance.
* <p>
* Do not use this method to create a true Map type -- use {@link #constructMapType} instead.
* Map-like types are only meant for supporting things that do not implement Map interface
* and as such cannot use standard Map handlers.
* </p>
* <p>
* NOTE: type modifiers are NOT called on constructed type itself; but are called
* for contained types.
*/
public MapLikeType constructMapLikeType(Class<?> mapClass, Class<?> keyClass, Class<?> valueClass) {
return constructMapLikeType(mapClass,
_fromClass(null, keyClass, EMPTY_BINDINGS),
_fromClass(null, valueClass, EMPTY_BINDINGS));
}
/**
* Method for constructing a {@link MapLikeType} instance
* <p>
* Do not use this method to create a true Map type -- use {@link #constructMapType} instead.
* Map-like types are only meant for supporting things that do not implement Map interface
* and as such cannot use standard Map handlers.
* </p>
* <p>
* NOTE: type modifiers are NOT called on constructed type itself.
*/
public MapLikeType constructMapLikeType(Class<?> mapClass, JavaType keyType, JavaType valueType) {
// 19-Oct-2015, tatu: Allow case of no-type-variables, since it seems likely to be
// a valid use case here
JavaType type = _fromClass(null, mapClass,
TypeBindings.createIfNeeded(mapClass, new JavaType[] { keyType, valueType }));
if (type instanceof MapLikeType) {
return (MapLikeType) type;
}
return MapLikeType.upgradeFrom(type, keyType, valueType);
}
/**
* Method for constructing a type instance with specified parameterization.
*<p>
* NOTE: type modifiers are NOT called on constructed type itself.
*/
public JavaType constructSimpleType(Class<?> rawType, JavaType[] parameterTypes) {
return _fromClass(null, rawType, TypeBindings.create(rawType, parameterTypes));
}
/**
* Method for constructing a {@link ReferenceType} instance with given type parameter
* (type MUST take one and only one type parameter)
*<p>
* NOTE: type modifiers are NOT called on constructed type itself.
*/
public JavaType constructReferenceType(Class<?> rawType, JavaType referredType)
{
return ReferenceType.construct(rawType,
TypeBindings.create(rawType, referredType), // [databind#2091]
null, null, // or super-class, interfaces?
referredType);
}
/**
* Factory method for constructing {@link JavaType} that
* represents a parameterized type. For example, to represent
* type {@code List<Set<Integer>>}, you could
* call
*<pre>
* JavaType inner = TypeFactory.constructParametricType(Set.class, Integer.class);
* return TypeFactory.constructParametricType(List.class, inner);
*</pre>
*
* @param parametrized Type-erased type to parameterize
* @param parameterClasses Type parameters to apply
*/
public JavaType constructParametricType(Class<?> parametrized, Class<?>... parameterClasses) {
int len = parameterClasses.length;
JavaType[] pt = new JavaType[len];
for (int i = 0; i < len; ++i) {
pt[i] = _fromClass(null, parameterClasses[i], EMPTY_BINDINGS);
}
return constructParametricType(parametrized, pt);
}
/**
* Factory method for constructing {@link JavaType} that
* represents a parameterized type. For example, to represent
* type {@code List<Set<Integer>>}, you could
*<pre>
* JavaType inner = TypeFactory.constructParametricType(Set.class, Integer.class);
* return TypeFactory.constructParametricType(List.class, inner);
*</pre>
*
* @param rawType Actual type-erased type
* @param parameterTypes Type parameters to apply
*
* @return Fully resolved type for given base type and type parameters
*/
public JavaType constructParametricType(Class<?> rawType, JavaType... parameterTypes)
{
return constructParametricType(rawType, TypeBindings.create(rawType, parameterTypes));
}