java - 在泛型类的静态类中使用泛型类型
问题描述
在一个安静的项目中,我正在尝试使用通用响应。在这个通用响应中,有一个静态 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 - 日期之间差异的平均值
- h2o - H2O autoML 在默认时间预算后不会停止
- kubernetes - 访问多个集群的参数
- ios - 在 iOS 上启动 BlueJeans 应用程序的 URL 方案?
- android-studio - 更改代码 > 拆分 > 设计的 Android Studio 键绑定
- bash - 如何根据主机名在 Bash 中自动设置提示颜色
- amazon-eks - 升级 EKS 集群时出现 AccessDenied 错误
- python - 如何在情节中为子情节添加标签?
- kubernetes - Azure 虚拟机规模集是否可以具有隐藏的公共 IP?
- kubernetes - Kubernetes 或任何其他编排工具上的一组容器的 CPU 限制