Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Data object fromJSON static factory methods #376

Merged
merged 1 commit into from
Nov 8, 2023
Merged

Conversation

vietj
Copy link
Member

@vietj vietj commented Nov 8, 2023

Let a data object to be converted from JSON with a factory method instead of a constructor. This enables interfaces to be data object and be convertible from JSON in data objects containing them.

@DataObject
public interface HostAndPort {

  static HostAndPort fromJson(JsonObject json) {
    int port = json.getInteger("port", -1);
    String host = json.getString("host");
    return of(host, port);
  }

  static HostAndPort of(String host, int port) {
    return new AutoMapped() {
      @Override
      public int port() {
        return port;
      }
      @Override
      public String host() {
        return host;
      }
      @Override
      public int hashCode() {
        return host.hashCode() + port;
      }
      @Override
      public boolean equals(Object obj) {
        HostAndPort that = (HostAndPort) obj;
        return Objects.equals(host(), that.host()) && port() == that.port();
      }
    };
  }

  int port();

  String host();

  default JsonObject toJson() {
    return new JsonObject().put("port", port()).put("host", host());
  }
}

In addition we also allow an interface to be annotated both with @VertxGen and @DataObject, this can be useful for avoiding to break backward compatibility.

…tead of a constructor. This enables interfaces to be data object and be convertible from JSON in data objects containing them.

In addition we also allow an interface to be annotated both with @VertxGen and @dataobject, this can be useful for avoiding to break backward compatibility.
@vietj vietj added this to the 5.0.0 milestone Nov 8, 2023
@vietj vietj self-assigned this Nov 8, 2023
@vietj vietj merged commit 2df3f55 into master Nov 8, 2023
4 checks passed
@vietj vietj deleted the auto-mapped-data-object branch November 8, 2023 23:10
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

Successfully merging this pull request may close these issues.

1 participant