[英]using generic type in static class of generic class
In a restful project, I'm trying to use a generic response. 在一个宁静的项目中,我试图使用通用响应。 In this generic response, there is a static responseBuilder.
在此通用响应中,有一个静态responseBuilder。 But the build method in responseBuilder cannot accept generic type.
但是responseBuilder中的build方法不能接受泛型。 Code :
代码:
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;
}
}
} }
When I use like this : RestResponseBuilder.ok().entity(null).build(); 当我这样使用时:RestResponseBuilder.ok()。entity(null).build(); There a warning : Type safety: The expression of type RestResponse needs unchecked conversion to conform to
出现警告:类型安全:RestResponse类型的表达式需要未经检查的转换才能符合
My question is, how can I add generic type in RestResponseBuilder to avoid this warning? 我的问题是,如何在RestResponseBuilder中添加泛型以避免这种警告? Thanks
谢谢
Don't use raw types. 不要使用原始类型。 Make your builder class generic, too, and its static methods generic, too:
也使构建器类通用,使其静态方法也通用:
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;
}
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.