gpt4 book ai didi

java - 在泛型类的静态类中使用泛型类型

转载 作者:行者123 更新时间:2023-12-02 10:35:09 25 4
gpt4 key购买 nike

在一个安静的项目中,我尝试使用通用响应。在这个通用响应中,有一个静态的responseBuilder。但是responseBuilder中的build方法不能接受泛型类型。代码:

public class RestResponse<T>{

private int status;

private String message;

private T entity;

/**
*
*/
public static class RestResponseBuilder {

private final RestResponse restResponse;

public RestResponseBuilder(RestResponse resp) {
this.restResponse = resp;
}

public static RestResponseBuilder ok() {

return status(HttpServletResponse.SC_OK).msg("ok");
}

public static RestResponseBuilder status(int status) {
final RestResponse resp = new RestResponse();
resp.setStatus(status);

return new RestResponseBuilder(resp);
}

public RestResponseBuilder msg(String msg) {
this.restResponse.setMessage(msg);
return this;
}

public RestResponseBuilder entity(Object entity) {
this.restResponse.setEntity(entity);
return this;
}

public RestResponse build() {

return restResponse;
}
}

}

当我这样使用时: RestResponseBuilder.ok().entity(null).build();有一个警告:类型安全:RestResponse 类型的表达式需要未经检查的转换才能符合

我的问题是,如何在 RestResponseBuilder 中添加泛型类型以避免此警告?谢谢

最佳答案

不要使用原始类型。使您的构建器类也通用,并且其静态方法也通用:

public class RestResponse<T> {

private int status;

private String message;

private T entity;

/**
*
*/
public static class RestResponseBuilder<T> {

private final RestResponse<T> restResponse;

public RestResponseBuilder(RestResponse<T> resp) {
this.restResponse = resp;
}

public static <T> RestResponseBuilder<T> ok() {

return RestResponseBuilder.<T>status(200).msg("ok");
}

public static <T> RestResponseBuilder<T> status(int status) {
final RestResponse<T> resp = new RestResponse<T>();
resp.status = status;

return new RestResponseBuilder<T>(resp);
}

public RestResponseBuilder<T> msg(String msg) {
this.restResponse.message = msg;
return this;
}

public RestResponseBuilder<T> entity(T entity) {
this.restResponse.entity = entity;
return this;
}

public RestResponse<T> build() {

return restResponse;
}
}

}

关于java - 在泛型类的静态类中使用泛型类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53350049/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com