通过 Java 中的接口继承 2 个共享 class?

Inheritance for 2 shared class via interface in Java?

在我们的 Java(Spring 启动)应用程序中,我们有一个基本请求 class,如下所示:

@Data
public class BaseRequest {
    @NotNull
    private UUID uuid;
}

从这个基础 class 扩展了 2 个用于创建和更新的请求,如下所示:

@Data
public class CreateRequest extends BaseRequest {

    @NotEmpty
    private String apiKey;

    @NotEmpty
    private String locationId;    
}
@Data
public class UpdateRequest extends BaseRequest {

    private String apiKey;

    private String locationId;    
}

这两个 class 之间的唯一区别是必填字段(在 CreateRequest 中是必需的,但在 UpdateRequest 中不是必填的。

下面是使用这两个请求的方法:

private void setRequest(SaveRequest request) {
    IntegrationRequest integrationRequest = new IntegrationRequest();
    integrationRequest.setApiKey(request.getApiKey());
    integrationRequest.setLocationId(request.getLocationId());

    // code omitted
}

由于字段不相同(必需/非必需),我必须重载此方法。但是我尝试通过传递另一个基础 class 扩展当前基础并继承这两个请求来使用单个 setRequest 方法,但由于一些未共享的字段,它不起作用。我也想使用接口,但是我真的很困惑我应该使用哪种方法来解决这个问题。

private void setRequest(UpdateRequest request) {
    IntegrationRequest integrationRequest = new IntegrationRequest();
    integrationRequest.setApiKey(request.getApiKey());
    integrationRequest.setLocationId(request.getLocationId());

    // code omitted
}

那么,有什么想法可以通过传递共享或基础 class/interface 来仅使用一个 setRequest 方法吗?

你可以这样做:

public interface Request {
    String getApiKey();
    String getLocationId();
}

@Data
public class CreateRequest extends BaseRequest implements Request {
    @NotEmpty
    private String apiKey;
    @NotEmpty
    private String locationId;
}

@Data
public class UpdateRequest extends BaseRequest implements Request {
    private String apiKey;
    private String locationId;
}

private void setRequest(Request request) {
    CreateRequest integrationRequest = new CreateRequest();
    integrationRequest.setApiKey(request.getApiKey());
    integrationRequest.setLocationId(request.getLocationId());

    // code omitted
}