-
-
Notifications
You must be signed in to change notification settings - Fork 1.4k
Description
Using Jackson 2.12.
One common pattern in code on my teams is to use 'alias' types to decorate otherwise primitive value types in APIs and/or for dimensional units to gain compiler support for detecting otherwise subtle programming errors (such as using the wrong unit or passing parameters in the wrong order).
Today, to do this with Java records, we need to write classes like
public record Watts(@JsonValue double value) {
@JsonCreator
public static Watts of(double value) {
return new Watts(value);
}
}
Without the @JsonCreator
annotated static method (or similarly trivial but verbose constructor), Jackson produces the error
com.fasterxml.jackson.databind.exc.MismatchedInputException: Cannot construct instance of `...Watts`
(although at least one Creator exists): no double/Double-argument constructor/factory method to
deserialize from Number value (<value>)
If we could place @JsonCreator
on record classes and infer use of the single argument default constructor I think it'd cut the boilerplate even more. Alternatively, or in addition, it might be interesting to infer that a record class with a single labeled @JsonValue
parameter should use the default constructor, allowing us to write either:
@JsonCreator
public record Watts(@JsonValue int value) {}
or
public record Watts(@JsonValue int value) {}