Skip to content

Allow auto-detection of Properties-based Constructor even if class has no-parameters (default) Constructor #5318

@cowtowncoder

Description

@cowtowncoder

(note: replacement for #5246)

Properties-based Constructor auto-detection works reliably for 2.x (iff jackson-parameter-names Module registered) and 3.x (without anything additional), for cases like this class:

public class Point {
  private final int x, y;

  public Point(int x, int y) {
    this.x = x;
    this.y. = y;
  }
}

(where 2-parameter Constructor is auto-detected for use without need for @JsonCreator or @JsonProperty annotations)

this fails if there are any other Constructors. And in particular, this will NOT auto-detect 2-parameter Constructor:

public class Point {
  private final int x, y;

  public Point() { this(0, 0); 
  // ^^^ prevents auto-detection; will be used instead!

  public Point(int x, int y) {
    this.x = x;
    this.y. = y;
  }
}

But we can change rules to allow this specific case so that auto-detection will work if:

  1. There is ONE visible (by default visibility rules, public) parameters-taking Constructor
  2. That Constructor has names for all Parameters (implicit from bytecode, or annotated)
  3. There MAY be a no-parameter (any visibility) -- aka "default" -- Constructor

where (3) is the changed rule (CANNOT -> MAY)

NOTE: for backwards-compatibility, there needs to be a way disable this feature:

ObjectMapper mapper = JsonMapper.nbuilder()
  .constructorDetector(ConstructorDetector.DEFAULT
        // by default is enabled, but we can disable
        .withAllowImplicitWithDefaultConstructor(false))
  .build();

to revert to 2.x handling where auto-detection is disabled.

Metadata

Metadata

Assignees

Labels

3.0Issue planned for initial 3.0 release3.0-release-notesIssues relevant for 3.0 release notes.

Type

No type

Projects

No projects

Relationships

None yet

Development

No branches or pull requests

Issue actions