eclipse-vertx / vertx-codegen

Vert.x code generator for asynchronous polyglot APIs
Apache License 2.0
105 stars 92 forks source link

Data object fromJSON static factory methods #376

Closed vietj closed 11 months ago

vietj commented 11 months ago

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.