-
-
Notifications
You must be signed in to change notification settings - Fork 1.4k
/
Copy pathPOJOPropertiesCollector.java
1824 lines (1663 loc) · 70.5 KB
/
POJOPropertiesCollector.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 com.fasterxml.jackson.databind.introspect;
import java.lang.reflect.Modifier;
import java.util.*;
import com.fasterxml.jackson.annotation.JacksonInject;
import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonFormat;
import com.fasterxml.jackson.databind.*;
import com.fasterxml.jackson.databind.cfg.ConstructorDetector;
import com.fasterxml.jackson.databind.cfg.HandlerInstantiator;
import com.fasterxml.jackson.databind.cfg.MapperConfig;
import com.fasterxml.jackson.databind.deser.impl.UnwrappedPropertyHandler;
import com.fasterxml.jackson.databind.jdk14.JDK14Util;
import com.fasterxml.jackson.databind.util.ClassUtil;
/**
* Helper class used for aggregating information about all possible
* properties of a POJO.
*/
public class POJOPropertiesCollector
{
/*
/**********************************************************
/* Configuration
/**********************************************************
*/
/**
* Configuration settings
*/
protected final MapperConfig<?> _config;
/**
* Handler used for name-mangling of getter, mutator (setter/with) methods
*
* @since 2.12
*/
protected final AccessorNamingStrategy _accessorNaming;
/**
* True if introspection is done for serialization (giving
* precedence for serialization annotations), or not (false, deserialization)
*/
protected final boolean _forSerialization;
/**
* Type of POJO for which properties are being collected.
*/
protected final JavaType _type;
/**
* Low-level introspected class information (methods, fields etc)
*/
protected final AnnotatedClass _classDef;
protected final VisibilityChecker<?> _visibilityChecker;
protected final AnnotationIntrospector _annotationIntrospector;
/**
* @since 2.9
*/
protected final boolean _useAnnotations;
/**
* @since 2.15
*/
protected final boolean _isRecordType;
/*
/**********************************************************
/* Collected property information
/**********************************************************
*/
/**
* State flag we keep to indicate whether actual property information
* has been collected or not.
*/
protected boolean _collected;
/**
* Set of logical property information collected so far.
*<p>
* Since 2.6, this has been constructed (more) lazily, to defer
* throwing of exceptions for potential conflicts in cases where
* this may not be an actual problem.
*/
protected LinkedHashMap<String, POJOPropertyBuilder> _properties;
protected List<POJOPropertyBuilder> _creatorProperties;
/**
* @since 2.18
*/
protected PotentialCreators _potentialCreators;
/**
* A set of "field renamings" that have been discovered, indicating
* intended renaming of other accessors: key is the implicit original
* name and value intended name to use instead.
*<p>
* Note that these renamings are applied earlier than "regular" (explicit)
* renamings and affect implicit name: their effect may be changed by
* further renaming based on explicit indicators.
* The main use case is to effectively relink accessors based on fields
* discovered, and used to sort of correct otherwise missing linkage between
* fields and other accessors.
*
* @since 2.11
*/
protected Map<PropertyName, PropertyName> _fieldRenameMappings;
protected LinkedList<AnnotatedMember> _anyGetters;
/**
* @since 2.12
*/
protected LinkedList<AnnotatedMember> _anyGetterField;
protected LinkedList<AnnotatedMethod> _anySetters;
protected LinkedList<AnnotatedMember> _anySetterField;
/**
* Accessors (field or "getter" method annotated with
* {@link com.fasterxml.jackson.annotation.JsonKey}
*
* @since 2.12
*/
protected LinkedList<AnnotatedMember> _jsonKeyAccessors;
/**
* Accessors (field or "getter" method) annotated with
* {@link com.fasterxml.jackson.annotation.JsonValue}
*/
protected LinkedList<AnnotatedMember> _jsonValueAccessors;
/**
* Lazily collected list of properties that can be implicitly
* ignored during serialization; only updated when collecting
* information for deserialization purposes
*/
protected HashSet<String> _ignoredPropertyNames;
/**
* Lazily collected list of members that were annotated to
* indicate that they represent mutators for deserializer
* value injection.
*/
protected LinkedHashMap<Object, AnnotatedMember> _injectables;
/**
* Lazily accessed information about POJO format overrides
*
* @since 2.17
*/
protected JsonFormat.Value _formatOverrides;
/*
/**********************************************************
/* Life-cycle
/**********************************************************
*/
/**
* @since 2.12
*/
protected POJOPropertiesCollector(MapperConfig<?> config, boolean forSerialization,
JavaType type, AnnotatedClass classDef,
AccessorNamingStrategy accessorNaming)
{
_config = config;
_forSerialization = forSerialization;
_type = type;
_classDef = classDef;
_isRecordType = _type.isRecordType();
if (config.isAnnotationProcessingEnabled()) {
_useAnnotations = true;
_annotationIntrospector = _config.getAnnotationIntrospector();
} else {
_useAnnotations = false;
_annotationIntrospector = AnnotationIntrospector.nopInstance();
}
_visibilityChecker = _config.getDefaultVisibilityChecker(type.getRawClass(),
classDef);
_accessorNaming = accessorNaming;
}
/*
/**********************************************************
/* Public API
/**********************************************************
*/
public MapperConfig<?> getConfig() {
return _config;
}
public JavaType getType() {
return _type;
}
/**
* @since 2.15
*/
public boolean isRecordType() {
return _isRecordType;
}
public AnnotatedClass getClassDef() {
return _classDef;
}
public AnnotationIntrospector getAnnotationIntrospector() {
return _annotationIntrospector;
}
public List<BeanPropertyDefinition> getProperties() {
// make sure we return a copy, so caller can remove entries if need be:
Map<String, POJOPropertyBuilder> props = getPropertyMap();
return new ArrayList<>(props.values());
}
// @since 2.18
public PotentialCreators getPotentialCreators() {
if (!_collected) {
collectAll();
}
return _potentialCreators;
}
public Map<Object, AnnotatedMember> getInjectables() {
if (!_collected) {
collectAll();
}
return _injectables;
}
/**
* @since 2.12
*/
public AnnotatedMember getJsonKeyAccessor() {
if (!_collected) {
collectAll();
}
// If @JsonKey defined, must have a single one
if (_jsonKeyAccessors != null) {
if (_jsonKeyAccessors.size() > 1) {
if (!_resolveFieldVsGetter(_jsonKeyAccessors)) {
reportProblem("Multiple 'as-key' properties defined (%s vs %s)",
_jsonKeyAccessors.get(0),
_jsonKeyAccessors.get(1));
}
}
// otherwise we won't greatly care
return _jsonKeyAccessors.get(0);
}
return null;
}
/**
* @since 2.9
*/
public AnnotatedMember getJsonValueAccessor()
{
if (!_collected) {
collectAll();
}
// If @JsonValue defined, must have a single one
// 15-Jan-2023, tatu: Except let's try resolving "getter-over-field" case at least
if (_jsonValueAccessors != null) {
if (_jsonValueAccessors.size() > 1) {
if (!_resolveFieldVsGetter(_jsonValueAccessors)) {
reportProblem("Multiple 'as-value' properties defined (%s vs %s)",
_jsonValueAccessors.get(0),
_jsonValueAccessors.get(1));
}
}
// otherwise we won't greatly care
return _jsonValueAccessors.get(0);
}
return null;
}
/**
* Alias for {@link #getAnyGetterMethod()}.
*
* @deprecated Since 2.12 use separate {@link #getAnyGetterMethod()} and
* {@link #getAnyGetterField()}.
*/
@Deprecated // since 2.12
public AnnotatedMember getAnyGetter() {
return getAnyGetterMethod();
}
/**
* @since 2.12 (before only had "getAnyGetter()")
*/
public AnnotatedMember getAnyGetterField()
{
if (!_collected) {
collectAll();
}
if (_anyGetterField != null) {
if (_anyGetterField.size() > 1) {
reportProblem("Multiple 'any-getter' fields defined (%s vs %s)",
_anyGetterField.get(0), _anyGetterField.get(1));
}
return _anyGetterField.getFirst();
}
return null;
}
/**
* @since 2.12 (before only had "getAnyGetter()")
*/
public AnnotatedMember getAnyGetterMethod()
{
if (!_collected) {
collectAll();
}
if (_anyGetters != null) {
if (_anyGetters.size() > 1) {
reportProblem("Multiple 'any-getter' methods defined (%s vs %s)",
_anyGetters.get(0), _anyGetters.get(1));
}
return _anyGetters.getFirst();
}
return null;
}
public AnnotatedMember getAnySetterField()
{
if (!_collected) {
collectAll();
}
if (_anySetterField != null) {
if (_anySetterField.size() > 1) {
reportProblem("Multiple 'any-setter' fields defined (%s vs %s)",
_anySetterField.get(0), _anySetterField.get(1));
}
return _anySetterField.getFirst();
}
return null;
}
public AnnotatedMethod getAnySetterMethod()
{
if (!_collected) {
collectAll();
}
if (_anySetters != null) {
if (_anySetters.size() > 1) {
reportProblem("Multiple 'any-setter' methods defined (%s vs %s)",
_anySetters.get(0), _anySetters.get(1));
}
return _anySetters.getFirst();
}
return null;
}
/**
* Accessor for set of properties that are explicitly marked to be ignored
* via per-property markers (but NOT class annotations).
*/
public Set<String> getIgnoredPropertyNames() {
return _ignoredPropertyNames;
}
/**
* Accessor to find out whether type specified requires inclusion
* of Object Identifier.
*/
public ObjectIdInfo getObjectIdInfo()
{
ObjectIdInfo info = _annotationIntrospector.findObjectIdInfo(_classDef);
if (info != null) { // 2.1: may also have different defaults for refs:
info = _annotationIntrospector.findObjectReferenceInfo(_classDef, info);
}
return info;
}
// Method called by main "getProperties()" method; left
// "protected" for unit tests
protected Map<String, POJOPropertyBuilder> getPropertyMap() {
if (!_collected) {
collectAll();
}
return _properties;
}
/**
* @since 2.17
*/
public JsonFormat.Value getFormatOverrides() {
if (_formatOverrides == null) {
JsonFormat.Value format = null;
// Let's check both per-type defaults and annotations;
// per-type defaults having higher precedence, so start with annotations
if (_annotationIntrospector != null) {
format = _annotationIntrospector.findFormat(_classDef);
}
JsonFormat.Value v = _config.getDefaultPropertyFormat(_type.getRawClass());
if (v != null) {
if (format == null) {
format = v;
} else {
format = format.withOverrides(v);
}
}
_formatOverrides = (format == null) ? JsonFormat.Value.empty() : format;
}
return _formatOverrides;
}
/*
/**********************************************************************
/* Public API: main-level collection
/**********************************************************************
*/
/**
* Internal method that will collect actual property information.
*
* @since 2.6
*/
protected void collectAll()
{
_potentialCreators = new PotentialCreators();
// First: gather basic accessors
LinkedHashMap<String, POJOPropertyBuilder> props = new LinkedHashMap<String, POJOPropertyBuilder>();
// 14-Nov-2024, tatu: Previously skipped checking fields for Records; with 2.18+ won't
// (see [databind#3628], [databind#3895], [databind#3992], [databind#4626])
_addFields(props); // note: populates _fieldRenameMappings
_addMethods(props);
// 25-Jan-2016, tatu: Avoid introspecting (constructor-)creators for non-static
// inner classes, see [databind#1502]
// 14-Nov-2024, tatu: Similarly need Creators for Records too (2.18+)
if (!_classDef.isNonStaticInnerClass()) {
_addCreators(props);
}
// Remove ignored properties, first; this MUST precede annotation merging
// since logic relies on knowing exactly which accessor has which annotation
_removeUnwantedProperties(props);
// and then remove unneeded accessors (wrt read-only, read-write)
_removeUnwantedAccessors(props);
// Rename remaining properties
_renameProperties(props);
// and now add injectables, but taking care to avoid overlapping ones
// via creator and regular properties
_addInjectables(props);
// then merge annotations, to simplify further processing
// 26-Sep-2017, tatu: Before 2.9.2 was done earlier but that prevented some of
// annotations from getting properly merged
for (POJOPropertyBuilder property : props.values()) {
property.mergeAnnotations(_forSerialization);
}
// And use custom naming strategy, if applicable...
// 18-Jan-2021, tatu: To be done before trimming, to resolve
// [databind#3368]
PropertyNamingStrategy naming = _findNamingStrategy();
if (naming != null) {
_renameUsing(props, naming);
}
// Sort by visibility (explicit over implicit); drop all but first of member
// type (getter, setter etc) if there is visibility difference
for (POJOPropertyBuilder property : props.values()) {
property.trimByVisibility();
}
// 22-Jul-2024, tatu: And now drop Record Fields once their effect
// (annotations) has been applied. But just for deserialization
if (_isRecordType && !_forSerialization) {
for (POJOPropertyBuilder property : props.values()) {
property.removeFields();
}
}
// and, if required, apply wrapper name: note, MUST be done after
// annotations are merged.
if (_config.isEnabled(MapperFeature.USE_WRAPPER_NAME_AS_PROPERTY_NAME)) {
_renameWithWrappers(props);
}
// well, almost last: there's still ordering...
_sortProperties(props);
_properties = props;
_collected = true;
}
/*
/**********************************************************************
/* Property introspection: Fields
/**********************************************************************
*/
/**
* Method for collecting basic information on all fields found
*/
protected void _addFields(Map<String, POJOPropertyBuilder> props)
{
final AnnotationIntrospector ai = _annotationIntrospector;
/* 28-Mar-2013, tatu: For deserialization we may also want to remove
* final fields, as often they won't make very good mutators...
* (although, maybe surprisingly, JVM _can_ force setting of such fields!)
*/
final boolean pruneFinalFields = !_forSerialization && !_config.isEnabled(MapperFeature.ALLOW_FINAL_FIELDS_AS_MUTATORS);
final boolean transientAsIgnoral = _config.isEnabled(MapperFeature.PROPAGATE_TRANSIENT_MARKER);
for (AnnotatedField f : _classDef.fields()) {
// @JsonKey?
if (Boolean.TRUE.equals(ai.hasAsKey(_config, f))) {
if (_jsonKeyAccessors == null) {
_jsonKeyAccessors = new LinkedList<>();
}
_jsonKeyAccessors.add(f);
}
// @JsonValue?
if (Boolean.TRUE.equals(ai.hasAsValue(f))) {
if (_jsonValueAccessors == null) {
_jsonValueAccessors = new LinkedList<>();
}
_jsonValueAccessors.add(f);
continue;
}
// 12-October-2020, dominikrebhan: [databind#1458] Support @JsonAnyGetter on
// fields and allow @JsonAnySetter to be declared as well.
boolean anyGetter = Boolean.TRUE.equals(ai.hasAnyGetter(f));
boolean anySetter = Boolean.TRUE.equals(ai.hasAnySetter(f));
if (anyGetter || anySetter) {
// @JsonAnyGetter?
if (anyGetter) {
if (_anyGetterField == null) {
_anyGetterField = new LinkedList<>();
}
_anyGetterField.add(f);
}
// @JsonAnySetter?
if (anySetter) {
if (_anySetterField == null) {
_anySetterField = new LinkedList<>();
}
_anySetterField.add(f);
// 07-Feb-2025: [databind#4775]: Skip the rest of processing, but only
// for "any-setter', not any-getter
continue;
}
}
String implName = ai.findImplicitPropertyName(f);
if (implName == null) {
implName = f.getName();
}
// 27-Aug-2020, tatu: [databind#2800] apply naming strategy for
// fields too, to allow use of naming conventions.
implName = _accessorNaming.modifyFieldName(f, implName);
if (implName == null) {
continue;
}
final PropertyName implNameP = _propNameFromSimple(implName);
// [databind#2527: Field-based renaming can be applied early (here),
// or at a later point, but probably must be done before pruning
// final fields. So let's do it early here
final PropertyName rename = ai.findRenameByField(_config, f, implNameP);
if ((rename != null) && !rename.equals(implNameP)) {
if (_fieldRenameMappings == null) {
_fieldRenameMappings = new HashMap<>();
}
_fieldRenameMappings.put(rename, implNameP);
}
PropertyName pn;
if (_forSerialization) {
// 18-Aug-2011, tatu: As per existing unit tests, we should only
// use serialization annotation (@JsonSerialize) when serializing
// fields, and similarly for deserialize-only annotations... so
// no fallbacks in this particular case.
pn = ai.findNameForSerialization(f);
} else {
pn = ai.findNameForDeserialization(f);
}
boolean hasName = (pn != null);
boolean nameExplicit = hasName;
if (nameExplicit && pn.isEmpty()) { // empty String meaning "use default name", here just means "same as field name"
pn = _propNameFromSimple(implName);
nameExplicit = false;
}
// having explicit name means that field is visible; otherwise need to check the rules
boolean visible = (pn != null);
if (!visible) {
visible = _visibilityChecker.isFieldVisible(f);
}
// and finally, may also have explicit ignoral
boolean ignored = ai.hasIgnoreMarker(f);
// 13-May-2015, tatu: Moved from earlier place (AnnotatedClass) in 2.6
if (f.isTransient()) {
// 20-May-2016, tatu: as per [databind#1184] explicit annotation should override
// "default" `transient`
if (!hasName) {
// 25-Nov-2022, tatu: [databind#3682] Drop transient Fields early;
// only retain if also have ignoral annotations (for name or ignoral)
if (transientAsIgnoral) {
ignored = true;
// 18-Jul-2023, tatu: [databind#3948] Need to retain if there was explicit
// ignoral marker
} else if (!ignored) {
continue;
}
}
}
/* [databind#190]: this is the place to prune final fields, if they are not
* to be used as mutators. Must verify they are not explicitly included.
* Also: if 'ignored' is set, need to include until a later point, to
* avoid losing ignoral information.
*/
if (pruneFinalFields && (pn == null) && !ignored
&& Modifier.isFinal(f.getModifiers())) {
continue;
}
_property(props, implName).addField(f, pn, nameExplicit, visible, ignored);
}
}
/*
/**********************************************************************
/* Property introspection: Creators (constructors, factory methods)
/**********************************************************************
*/
// Completely rewritten in 2.18
protected void _addCreators(Map<String, POJOPropertyBuilder> props)
{
final PotentialCreators creators = _potentialCreators;
// First, resolve explicit annotations for all potential Creators
// (but do NOT filter out DISABLED ones yet!)
List<PotentialCreator> constructors = _collectCreators(_classDef.getConstructors());
List<PotentialCreator> factories = _collectCreators(_classDef.getFactoryMethods());
// Then find what is the Primary Constructor (if one exists for type):
// for Java Records and potentially other types too ("data classes"):
// Needs to be done early to get implicit names populated
final PotentialCreator primaryCreator;
if (_isRecordType) {
primaryCreator = JDK14Util.findCanonicalRecordConstructor(_config, _classDef, constructors);
} else {
// 02-Nov-2024, tatu: Alas, naming here is confusing: method properly
// should have been "findPrimaryCreator()" so as not to confused with
// 0-args default Creators...
primaryCreator = _annotationIntrospector.findDefaultCreator(_config, _classDef,
constructors, factories);
}
// Next: remove creators marked as explicitly disabled
_removeDisabledCreators(constructors);
_removeDisabledCreators(factories);
// And then remove non-annotated static methods that do not look like factories
_removeNonFactoryStaticMethods(factories, primaryCreator);
// and use annotations to find explicitly chosen Creators
if (_useAnnotations) { // can't have explicit ones without Annotation introspection
// Start with Constructors as they have higher precedence:
_addExplicitlyAnnotatedCreators(creators, constructors, props, false);
// followed by Factory methods (lower precedence)
_addExplicitlyAnnotatedCreators(creators, factories, props,
creators.hasPropertiesBased());
}
// If no Explicitly annotated creators (or Primary one) found, look
// for ones with explicitly-named ({@code @JsonProperty}) parameters
if (!creators.hasPropertiesBased()) {
// only discover constructor Creators?
_addCreatorsWithAnnotatedNames(creators, constructors, primaryCreator);
}
// But if no annotation-based Creators found, find/use Primary Creator
// detected earlier, if any
if (primaryCreator != null) {
// ... but only process if still included as a candidate
if (constructors.remove(primaryCreator)
|| factories.remove(primaryCreator)) {
// and then consider delegating- vs properties-based
if (_isDelegatingConstructor(primaryCreator)) {
// 08-Oct-2024, tatu: [databind#4724] Only add if no explicit
// candidates added
if (!creators.hasDelegating()) {
// ... not technically explicit but simpler this way
creators.addExplicitDelegating(primaryCreator);
}
} else { // primary creator is properties-based
if (!creators.hasPropertiesBased()) {
creators.setPropertiesBased(_config, primaryCreator, "Primary");
}
}
}
}
// One more thing: if neither explicit (constructor or factory) nor
// canonical (constructor?), consider implicit Constructor with all named.
final ConstructorDetector ctorDetector = _config.getConstructorDetector();
if (!creators.hasPropertiesBasedOrDelegating()
&& !ctorDetector.requireCtorAnnotation()) {
// But only if no Default (0-args) constructor available OR if we are configured
// to prefer properties-based Creators
if ((_classDef.getDefaultConstructor() == null)
|| ctorDetector.singleArgCreatorDefaultsToProperties()) {
_addImplicitConstructor(creators, constructors, props);
}
}
// Anything else left, add as possible implicit Creators
// ... but first, trim non-visible
_removeNonVisibleCreators(constructors);
_removeNonVisibleCreators(factories);
creators.setImplicitDelegating(constructors, factories);
// And finally add logical properties for the One Properties-based
// creator selected (if any):
PotentialCreator propsCtor = creators.propertiesBased;
if (propsCtor == null) {
_creatorProperties = Collections.emptyList();
} else {
_creatorProperties = new ArrayList<>();
_addCreatorParams(props, propsCtor, _creatorProperties);
}
}
// Method to determine if given non-explictly-annotated constructor
// looks like delegating one
private boolean _isDelegatingConstructor(PotentialCreator ctor)
{
// First things first: could be
switch (ctor.creatorModeOrDefault()) {
case DELEGATING:
return true;
case DISABLED:
case PROPERTIES:
return false;
default:
}
// Only consider single-arg case, for now
if (ctor.paramCount() == 1) {
// Main thing: @JsonValue makes it delegating:
if ((_jsonValueAccessors != null) && !_jsonValueAccessors.isEmpty()) {
return true;
}
}
return false;
}
private List<PotentialCreator> _collectCreators(List<? extends AnnotatedWithParams> ctors)
{
if (ctors.isEmpty()) {
return Collections.emptyList();
}
List<PotentialCreator> result = new ArrayList<>();
for (AnnotatedWithParams ctor : ctors) {
JsonCreator.Mode creatorMode = _useAnnotations
? _annotationIntrospector.findCreatorAnnotation(_config, ctor) : null;
// 06-Jul-2024, tatu: Can't yet drop DISABLED ones; add all (for now)
result.add(new PotentialCreator(ctor, creatorMode));
}
return (result == null) ? Collections.emptyList() : result;
}
private void _removeDisabledCreators(List<PotentialCreator> ctors)
{
Iterator<PotentialCreator> it = ctors.iterator();
while (it.hasNext()) {
// explicitly prevented? Remove
if (it.next().creatorMode() == JsonCreator.Mode.DISABLED) {
it.remove();
}
}
}
private void _removeNonVisibleCreators(List<PotentialCreator> ctors)
{
Iterator<PotentialCreator> it = ctors.iterator();
while (it.hasNext()) {
PotentialCreator ctor = it.next();
if (!_visibilityChecker.isCreatorVisible(ctor.creator())) {
it.remove();
}
}
}
private void _removeNonFactoryStaticMethods(List<PotentialCreator> ctors,
PotentialCreator primaryCreator)
{
final Class<?> rawType = _type.getRawClass();
Iterator<PotentialCreator> it = ctors.iterator();
while (it.hasNext()) {
// explicit mode? Retain (for now)
PotentialCreator ctor = it.next();
if (ctor.isAnnotated()) {
continue;
}
// Do not trim Primary creator either
if (primaryCreator == ctor) {
continue;
}
// Copied from `BasicBeanDescription.isFactoryMethod()`
AnnotatedWithParams factory = ctor.creator();
if (rawType.isAssignableFrom(factory.getRawType())
&& ctor.paramCount() == 1) {
String name = factory.getName();
if ("valueOf".equals(name)) {
continue;
} else if ("fromString".equals(name)) {
Class<?> cls = factory.getRawParameterType(0);
if (cls == String.class || CharSequence.class.isAssignableFrom(cls)) {
continue;
}
}
}
it.remove();
}
}
private void _addExplicitlyAnnotatedCreators(PotentialCreators collector,
List<PotentialCreator> ctors,
Map<String, POJOPropertyBuilder> props,
boolean skipPropsBased)
{
final ConstructorDetector ctorDetector = _config.getConstructorDetector();
Iterator<PotentialCreator> it = ctors.iterator();
while (it.hasNext()) {
PotentialCreator ctor = it.next();
// If no explicit annotation, skip for now (may be discovered
// at a later point)
if (!ctor.isAnnotated()) {
continue;
}
it.remove();
boolean isPropsBased;
switch (ctor.creatorMode()) {
case DELEGATING:
isPropsBased = false;
break;
case PROPERTIES:
isPropsBased = true;
break;
case DEFAULT:
default:
isPropsBased = _isExplicitlyAnnotatedCreatorPropsBased(ctor,
props, ctorDetector);
}
if (isPropsBased) {
// Skipping done if we already got higher-precedence Creator
if (!skipPropsBased) {
collector.setPropertiesBased(_config, ctor, "explicit");
}
} else {
collector.addExplicitDelegating(ctor);
}
}
}
private boolean _isExplicitlyAnnotatedCreatorPropsBased(PotentialCreator ctor,
Map<String, POJOPropertyBuilder> props, ConstructorDetector ctorDetector)
{
if (ctor.paramCount() == 1) {
// Is ambiguity/heuristics allowed?
switch (ctorDetector.singleArgMode()) {
case DELEGATING:
return false;
case PROPERTIES:
return true;
case REQUIRE_MODE:
throw new IllegalArgumentException(String.format(
"Single-argument constructor (%s) is annotated but no 'mode' defined; `ConstructorDetector`"
+ "configured with `SingleArgConstructor.REQUIRE_MODE`",
ctor.creator()));
case HEURISTIC:
default:
}
}
// First: if explicit names found, is Properties-based
ctor.introspectParamNames(_config);
if (ctor.hasExplicitNames()) {
return true;
}
// Second: [databind#3180] @JsonValue indicates delegating
if ((_jsonValueAccessors != null) && !_jsonValueAccessors.isEmpty()) {
return false;
}
if (ctor.paramCount() == 1) {
// One more possibility: implicit name that maps to implied
// property with at least one visible accessor
PropertyName paramName = ctor.implicitName(0);
if (paramName != null) {
POJOPropertyBuilder prop = props.get(paramName.getSimpleName());
if (prop != null) {
if (prop.anyVisible() && !prop.anyIgnorals()) {
return true;
}
} else {
// 26-Nov-2024, tatu: [databind#4810] Implicit name not always
// enough; may need to link to explicit name override
for (POJOPropertyBuilder pb : props.values()) {
if (pb.anyVisible()
&& !pb.anyIgnorals()
&& pb.hasExplicitName(paramName)) {
return true;
}
}
}
}
// Second: injectable also suffices
if ((_annotationIntrospector != null)
&& _annotationIntrospector.findInjectableValue(ctor.param(0)) != null) {
return true;
}
return false;
}
// Trickiest case: rely on existence of implicit names and/or injectables
return ctor.hasNameOrInjectForAllParams(_config);
}
private void _addCreatorsWithAnnotatedNames(PotentialCreators collector,
List<PotentialCreator> ctors, PotentialCreator primaryCtor)
{
final List<PotentialCreator> found = _findCreatorsWithAnnotatedNames(ctors);
// 16-Jul-2024, tatu: [databind#4620] If Primary Creator found, it
// will be used to resolve candidate to use, if any
if (primaryCtor != null) {
if (found.contains(primaryCtor)) {
collector.setPropertiesBased(_config, primaryCtor, "implicit");
return;
}
}
for (PotentialCreator ctor : found) {
collector.setPropertiesBased(_config, ctor, "implicit");
}
}
private List<PotentialCreator> _findCreatorsWithAnnotatedNames(List<PotentialCreator> ctors)
{
List<PotentialCreator> found = null;
Iterator<PotentialCreator> it = ctors.iterator();
while (it.hasNext()) {
PotentialCreator ctor = it.next();
// Ok: existence of explicit (annotated) names infers properties-based:
ctor.introspectParamNames(_config);
if (!ctor.hasExplicitNames()) {
continue;
}
it.remove();
if (found == null) {
found = new ArrayList<>(4);
}
found.add(ctor);
}
return (found == null) ? Collections.emptyList() : found;
}
private boolean _addImplicitConstructor(PotentialCreators collector,
List<PotentialCreator> ctors, Map<String, POJOPropertyBuilder> props)
{
// Must have one and only one candidate
if (ctors.size() != 1) {
return false;
}
final PotentialCreator ctor = ctors.get(0);
// which needs to be visible
if (!_visibilityChecker.isCreatorVisible(ctor.creator())) {
return false;
}
ctor.introspectParamNames(_config);
// As usual, 1-param case is distinct
if (ctor.paramCount() != 1) {
if (!ctor.hasNameOrInjectForAllParams(_config)) {
return false;