aboutsummaryrefslogtreecommitdiff
path: root/src/main/java/com/fasterxml/jackson/databind/deser/ValueInstantiator.java
blob: 572e99bbcf7f5d508b28d93270659207b7cc2b53 (plain)
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
package com.fasterxml.jackson.databind.deser;

import java.io.IOException;

import com.fasterxml.jackson.databind.*;
import com.fasterxml.jackson.databind.cfg.CoercionAction;
import com.fasterxml.jackson.databind.cfg.CoercionInputShape;
import com.fasterxml.jackson.databind.deser.impl.PropertyValueBuffer;
import com.fasterxml.jackson.databind.introspect.AnnotatedWithParams;
import com.fasterxml.jackson.databind.type.LogicalType;

/**
 * Class that defines simple API implemented by objects that create value
 * instances.  Some or all of properties of value instances may 
 * be initialized by instantiator, rest being populated by deserializer,
 * to which value instance is passed.
 * Since different kinds of JSON values (structured and scalar)
 * may be bound to Java values, in some cases instantiator
 * fully defines resulting value; this is the case when JSON value
 * is a scalar value (String, number, boolean).
 *<p>
 * Note that this type is not parameterized (even though it would seemingly
 * make sense), because such type information cannot be use effectively
 * during runtime: access is always using either wildcard type, or just
 * basic {@link java.lang.Object}; and so adding type parameter seems
 * like unnecessary extra work.
 *<p>
 * Actual implementations are strongly recommended to be based on
 * {@link com.fasterxml.jackson.databind.deser.std.StdValueInstantiator}
 * which implements all methods, and as such will be compatible
 * across versions even if new methods were added to this interface.
 */
public abstract class ValueInstantiator
{
    /*
    /**********************************************************
    /* Introspection
    /**********************************************************
     */

    /**
     * @since 2.9
     */
    public interface Gettable {
        public ValueInstantiator getValueInstantiator();
    }

    /*
    /**********************************************************
    /* Life-cycle
    /**********************************************************
     */

    /**
     * "Contextualization" method that is called after construction but before first
     * use, to allow instantiator access to context needed to possible resolve its
     * dependencies.
     *
     * @param ctxt Currently active deserialization context: needed to (for example)
     *    resolving {@link com.fasterxml.jackson.databind.jsontype.TypeDeserializer}s.
     *
     * @return This instance, if no change, or newly constructed instance
     *
     * @throws JsonMappingException If there are issues with contextualization
     *
     * @since 2.12
     */
    public ValueInstantiator createContextual(DeserializationContext ctxt, BeanDescription beanDesc)
            throws JsonMappingException
    {
        return this;
    }

    /*
    /**********************************************************
    /* Metadata accessors
    /**********************************************************
     */

    /**
     * Accessor for raw (type-erased) type of instances to create.
     *<p>
     * NOTE: since this method has not existed since beginning of
     * Jackson 2.0 series, default implementation will just return
     * <code>Object.class</code>; implementations are expected
     * to override it with real value.
     *
     * @since 2.8
     */
    public Class<?> getValueClass() {
        return Object.class;
    }

    /**
     * Method that returns description of the value type this instantiator
     * handles. Used for error messages, diagnostics.
     */
    public String getValueTypeDesc() {
        Class<?> cls = getValueClass();
        if (cls == null) {
            return "UNKNOWN";
        }
        return cls.getName();
    }

    /**
     * Method that will return true if any of {@code canCreateXxx} method
     * returns true: that is, if there is any way that an instance could
     * be created.
     */
    public boolean canInstantiate() {
        return canCreateUsingDefault()
                || canCreateUsingDelegate() || canCreateUsingArrayDelegate()
                || canCreateFromObjectWith() || canCreateFromString()
                || canCreateFromInt() || canCreateFromLong()
                || canCreateFromDouble() || canCreateFromBoolean();
    }

    /**
     * Method that can be called to check whether a String-based creator
     * is available for this instantiator.
     *<p>
     * NOTE: does NOT include possible case of fallbacks, or coercion; only
     * considers explicit creator.
     */
    public boolean canCreateFromString() { return false; }

    /**
     * Method that can be called to check whether an integer (int, Integer) based
     * creator is available to use (to call {@link #createFromInt}).
     */
    public boolean canCreateFromInt() { return false; }

    /**
     * Method that can be called to check whether a long (long, Long) based
     * creator is available to use (to call {@link #createFromLong}).
     */
    public boolean canCreateFromLong() { return false; }

    /**
     * Method that can be called to check whether a double (double / Double) based
     * creator is available to use (to call {@link #createFromDouble}).
     */
    public boolean canCreateFromDouble() { return false; }

    /**
     * Method that can be called to check whether a double (boolean / Boolean) based
     * creator is available to use (to call {@link #createFromDouble}).
     */
    public boolean canCreateFromBoolean() { return false; }

    /**
     * Method that can be called to check whether a default creator (constructor,
     * or no-arg static factory method)
     * is available for this instantiator
     */
    public boolean canCreateUsingDefault() {  return getDefaultCreator() != null; }

    /**
     * Method that can be called to check whether a delegate-based creator (single-arg
     * constructor or factory method)
     * is available for this instantiator
     */
    public boolean canCreateUsingDelegate() { return false; }

    /**
     * Method that can be called to check whether a array-delegate-based creator
     * (single-arg constructor or factory method)
     * is available for this instantiator
     *
     * @since 2.7
     */
    public boolean canCreateUsingArrayDelegate() { return false; }

    /**
     * Method that can be called to check whether a property-based creator
     * (argument-taking constructor or factory method)
     * is available to instantiate values from JSON Object
     */
    public boolean canCreateFromObjectWith() { return false; }

    /**
     * Method called to determine types of instantiation arguments
     * to use when creating instances with creator arguments
     * (when {@link #canCreateFromObjectWith()} returns  true).
     * These arguments are bound from JSON, using specified
     * property types to locate deserializers.
     *<p>
     * NOTE: all properties will be of type
     * {@link com.fasterxml.jackson.databind.deser.CreatorProperty}.
     */
    public SettableBeanProperty[] getFromObjectArguments(DeserializationConfig config) {
        return null;
    }

    /**
     * Method that can be used to determine what is the type of delegate
     * type to use, if any; if no delegates are used, will return null.
     * If non-null type is returned, deserializer will bind JSON into
     * specified type (using standard deserializer for that type), and
     * pass that to instantiator.
     */
    public JavaType getDelegateType(DeserializationConfig config) { return null; }

    /**
     * Method that can be used to determine what is the type of array delegate
     * type to use, if any; if no delegates are used, will return null. If
     * non-null type is returned, deserializer will bind JSON into specified
     * type (using standard deserializer for that type), and pass that to
     * instantiator.
     *
     * @since 2.7
     */
    public JavaType getArrayDelegateType(DeserializationConfig config) { return null; }

    /*
    /**********************************************************
    /* Instantiation methods for JSON Object
    /**********************************************************
     */

    /**
     * Method called to create value instance from a JSON value when
     * no data needs to passed to creator (constructor, factory method);
     * typically this will call the default constructor of the value object.
     * It will only be used if more specific creator methods are not
     * applicable; hence "default".
     *<p>
     * This method is called if {@link #getFromObjectArguments} returns
     * null or empty List.
     */
    public Object createUsingDefault(DeserializationContext ctxt) throws IOException {
        return ctxt.handleMissingInstantiator(getValueClass(), this, null,
                "no default no-arguments constructor found");
    }

    /**
     * Method called to create value instance from JSON Object when
     * instantiation arguments are passed; this is done, for example when passing information
     * specified with "Creator" annotations.
     *<p>
     * This method is called if {@link #getFromObjectArguments} returns
     * a non-empty List of arguments.
     */
    public Object createFromObjectWith(DeserializationContext ctxt, Object[] args) throws IOException {
        // sanity check; shouldn't really get called if no Creator specified
        return ctxt.handleMissingInstantiator(getValueClass(), this, null,
                "no creator with arguments specified");
    }

    /**
     * Method that delegates to
     * {@link #createFromObjectWith(DeserializationContext, Object[])} by
     * default, but can be overridden if the application should have customized
     * behavior with respect to missing properties.
     *<p>
     * The default implementation of this method uses
     * {@link PropertyValueBuffer#getParameters(SettableBeanProperty[])} to read
     * and validate all properties in bulk, possibly substituting defaults for
     * missing properties or throwing exceptions for missing properties.  An
     * overridden implementation of this method could, for example, use
     * {@link PropertyValueBuffer#hasParameter(SettableBeanProperty)} and
     * {@link PropertyValueBuffer#getParameter(SettableBeanProperty)} to safely
     * read the present properties only, and to have some other behavior for the
     * missing properties.
     * 
     * @since 2.8
     */
    public Object createFromObjectWith(DeserializationContext ctxt,
            SettableBeanProperty[] props, PropertyValueBuffer buffer)
        throws IOException
    {
        return createFromObjectWith(ctxt, buffer.getParameters(props));
    }

    /**
     * Method to called to create value instance from JSON Object using
     * an intermediate "delegate" value to pass to createor method
     */
    public Object createUsingDelegate(DeserializationContext ctxt, Object delegate) throws IOException {
        return ctxt.handleMissingInstantiator(getValueClass(), this, null,
                "no delegate creator specified");
    }

    /**
     * Method to called to create value instance from JSON Array using
     * an intermediate "delegate" value to pass to createor method
     */
    public Object createUsingArrayDelegate(DeserializationContext ctxt, Object delegate) throws IOException {
        return ctxt.handleMissingInstantiator(getValueClass(), this, null,
                "no array delegate creator specified");
    }

    /*
    /**********************************************************
    /* Instantiation methods for JSON scalar types (String, Number, Boolean)
    /**********************************************************
     */

    public Object createFromString(DeserializationContext ctxt, String value) throws IOException {
        return ctxt.handleMissingInstantiator(getValueClass(), this, ctxt.getParser(),
                "no String-argument constructor/factory method to deserialize from String value ('%s')",
                value);

    }

    public Object createFromInt(DeserializationContext ctxt, int value) throws IOException {
        return ctxt.handleMissingInstantiator(getValueClass(), this, null,
                "no int/Int-argument constructor/factory method to deserialize from Number value (%s)",
                value);
    }

    public Object createFromLong(DeserializationContext ctxt, long value) throws IOException {
        return ctxt.handleMissingInstantiator(getValueClass(), this, null,
                "no long/Long-argument constructor/factory method to deserialize from Number value (%s)",
                value);
    }

    public Object createFromDouble(DeserializationContext ctxt, double value) throws IOException {
        return ctxt.handleMissingInstantiator(getValueClass(), this, null,
                "no double/Double-argument constructor/factory method to deserialize from Number value (%s)",
                value);
    }

    public Object createFromBoolean(DeserializationContext ctxt, boolean value) throws IOException {
        return ctxt.handleMissingInstantiator(getValueClass(), this, null,
                "no boolean/Boolean-argument constructor/factory method to deserialize from boolean value (%s)",
                value);
    }

    /*
    /**********************************************************
    /* Accessors for underlying creator objects (optional)
    /**********************************************************
     */

    /**
     * Method that can be called to try to access member (constructor,
     * static factory method) that is used as the "default creator"
     * (creator that is called without arguments; typically default
     * [zero-argument] constructor of the type).
     * Note that implementations not required to return actual object
     * they use (or, they may use some other instantiation) method.
     * That is, even if {@link #canCreateUsingDefault()} returns true,
     * this method may return null .
     */
    public AnnotatedWithParams getDefaultCreator() { return null; }

    /**
     * Method that can be called to try to access member (constructor,
     * static factory method) that is used as the "delegate creator".
     * Note that implementations not required to return actual object
     * they use (or, they may use some other instantiation) method.
     * That is, even if {@link #canCreateUsingDelegate()} returns true,
     * this method may return null .
     */
    public AnnotatedWithParams getDelegateCreator() { return null; }

    /**
     * Method that can be called to try to access member (constructor,
     * static factory method) that is used as the "array delegate creator".
     * Note that implementations not required to return actual object
     * they use (or, they may use some other instantiation) method.
     * That is, even if {@link #canCreateUsingArrayDelegate()} returns true,
     * this method may return null .
     */
    public AnnotatedWithParams getArrayDelegateCreator() { return null; }

    /**
     * Method that can be called to try to access member (constructor,
     * static factory method) that is used as the "non-default creator"
     * (constructor or factory method that takes one or more arguments).
     * Note that implementations not required to return actual object
     * they use (or, they may use some other instantiation) method.
     * That is, even if {@link #canCreateFromObjectWith()} returns true,
     * this method may return null .
     */
    public AnnotatedWithParams getWithArgsCreator() { return null; }

    /*
    /**********************************************************
    /* Helper methods
    /**********************************************************
     */

    /**
     * @since 2.4 (demoted from <code>StdValueInstantiator</code>)
     * @deprecated Since 2.12 should not handle coercions here
     */
    @Deprecated // since 2.12
    protected Object _createFromStringFallbacks(DeserializationContext ctxt, String value)
            throws IOException
    {
        // also, empty Strings might be accepted as null Object...
        if (value.length() == 0) {
            if (ctxt.isEnabled(DeserializationFeature.ACCEPT_EMPTY_STRING_AS_NULL_OBJECT)) {
                return null;
            }
        }

        /* 28-Sep-2011, tatu: Ok this is not clean at all; but since there are legacy
         *   systems that expect conversions in some cases, let's just add a minimal
         *   patch (note: same could conceivably be used for numbers too).
         */
        if (canCreateFromBoolean()) {
            // 29-May-2020, tatu: With 2.12 can and should use CoercionConfig so:
            if (ctxt.findCoercionAction(LogicalType.Boolean, Boolean.class,
                    CoercionInputShape.String) == CoercionAction.TryConvert) {
                String str = value.trim();
                if ("true".equals(str)) {
                    return createFromBoolean(ctxt, true);
                }
                if ("false".equals(str)) {
                    return createFromBoolean(ctxt, false);
                }
            }
        }
        return ctxt.handleMissingInstantiator(getValueClass(), this, ctxt.getParser(),
                "no String-argument constructor/factory method to deserialize from String value ('%s')",
                value);
    }

    /*
    /**********************************************************
    /* Standard Base implementation (since 2.8)
    /**********************************************************
     */

    /**
     * Partial {@link ValueInstantiator} implementation that is strongly recommended
     * to be used instead of directly extending {@link ValueInstantiator} itself.
     */
    public static class Base extends ValueInstantiator
        implements java.io.Serializable // just because used as base for "standard" variants
    {
        private static final long serialVersionUID = 1L;

        protected final Class<?> _valueType;

        public Base(Class<?> type) {
            _valueType = type;
        }

        public Base(JavaType type) {
            _valueType = type.getRawClass();
        }
        
        @Override
        public String getValueTypeDesc() {
            return _valueType.getName();
        }

        @Override
        public Class<?> getValueClass() {
            return _valueType;
        }
    }

    /**
     * Delegating {@link ValueInstantiator} implementation meant as a base type
     * that by default delegates methods to specified fallback instantiator.
     *
     * @since 2.12
     */
    public static class Delegating extends ValueInstantiator
        implements java.io.Serializable
    {
        private static final long serialVersionUID = 1L;

        protected final ValueInstantiator _delegate;
        
        protected Delegating(ValueInstantiator delegate) {
            _delegate = delegate;
        }

        @Override
        public ValueInstantiator createContextual(DeserializationContext ctxt,  BeanDescription beanDesc)
                throws JsonMappingException
        {
            ValueInstantiator d = _delegate.createContextual(ctxt, beanDesc);
            return (d == _delegate) ? this : new Delegating(d);
        }

        protected ValueInstantiator delegate() { return _delegate; }

        @Override
        public Class<?> getValueClass() { return delegate().getValueClass(); }

        @Override
        public String getValueTypeDesc() { return delegate().getValueTypeDesc(); }

        @Override
        public boolean canInstantiate() { return delegate().canInstantiate(); }

        @Override
        public boolean canCreateFromString() { return delegate().canCreateFromString(); }
        @Override
        public boolean canCreateFromInt() { return delegate().canCreateFromInt(); }
        @Override
        public boolean canCreateFromLong() { return delegate().canCreateFromLong(); }
        @Override
        public boolean canCreateFromDouble() { return delegate().canCreateFromDouble(); }
        @Override
        public boolean canCreateFromBoolean() { return delegate().canCreateFromBoolean(); }
        @Override
        public boolean canCreateUsingDefault() { return delegate().canCreateUsingDefault(); }
        @Override
        public boolean canCreateUsingDelegate() { return delegate().canCreateUsingDelegate(); }
        @Override
        public boolean canCreateUsingArrayDelegate() { return delegate().canCreateUsingArrayDelegate(); }
        @Override
        public boolean canCreateFromObjectWith() { return delegate().canCreateFromObjectWith(); }

        @Override
        public SettableBeanProperty[] getFromObjectArguments(DeserializationConfig config) {
            return delegate().getFromObjectArguments(config);
        }

        @Override
        public JavaType getDelegateType(DeserializationConfig config) {
            return delegate().getDelegateType(config);
        }

        @Override
        public JavaType getArrayDelegateType(DeserializationConfig config) {
            return delegate().getArrayDelegateType(config);
        }

        /*
        /**********************************************************
        /* Creation methods
        /**********************************************************
         */

        @Override
        public Object createUsingDefault(DeserializationContext ctxt) throws IOException {
            return delegate().createUsingDefault(ctxt);
        }

        @Override
        public Object createFromObjectWith(DeserializationContext ctxt, Object[] args) throws IOException {
            return delegate().createFromObjectWith(ctxt, args);
        }

        @Override
        public Object createFromObjectWith(DeserializationContext ctxt,
                SettableBeanProperty[] props, PropertyValueBuffer buffer)
            throws IOException {
            return delegate().createFromObjectWith(ctxt, props, buffer);
        }

        @Override
        public Object createUsingDelegate(DeserializationContext ctxt, Object delegate) throws IOException {
            return delegate().createUsingDelegate(ctxt, delegate);
        }

        @Override
        public Object createUsingArrayDelegate(DeserializationContext ctxt, Object delegate) throws IOException {
            return delegate().createUsingArrayDelegate(ctxt, delegate);
        }

        @Override
        public Object createFromString(DeserializationContext ctxt, String value) throws IOException {
            return delegate().createFromString(ctxt, value);
        }

        @Override
        public Object createFromInt(DeserializationContext ctxt, int value) throws IOException {
            return delegate().createFromInt(ctxt, value);
        }

        @Override
        public Object createFromLong(DeserializationContext ctxt, long value) throws IOException {
            return delegate().createFromLong(ctxt, value);
        }

        @Override
        public Object createFromDouble(DeserializationContext ctxt, double value) throws IOException {
            return delegate().createFromDouble(ctxt, value);
        }

        @Override
        public Object createFromBoolean(DeserializationContext ctxt, boolean value) throws IOException {
            return delegate().createFromBoolean(ctxt, value);
        }

        /*
        /**********************************************************
        /* Accessors for underlying creator objects (optional)
        /**********************************************************
         */

        @Override
        public AnnotatedWithParams getDefaultCreator() { return delegate().getDefaultCreator(); }

        @Override
        public AnnotatedWithParams getDelegateCreator() { return delegate().getDelegateCreator(); }

        @Override
        public AnnotatedWithParams getArrayDelegateCreator() { return delegate().getArrayDelegateCreator(); }

        @Override
        public AnnotatedWithParams getWithArgsCreator() { return delegate().getWithArgsCreator(); }
    }
}