java使用泛型定义结果集
介绍
写三个文件ResultsCode.java
、ResponseData.java
、Result.java
,使用泛型让java项目中返回结果集,能够提高代码的可读性、可维护性和可扩展性
代码
ResultsCode.java
:
package com.rds.study.pojo;
public enum ResultsCode {
SUCCESS(200, "操作成功"),
ERROR(500, "服务器异常"),
UNAUTHORIZED(401, "未认证(签名错误)"),
NOT_FOUNT(404, "接口不存在");
public int code;
public String message;
ResultsCode(int code, String message) {
this.code = code;
this.message = message;
}
}
ResponseData.java
:
package com.rds.study.pojo;
public class ResponseData {
public static <T> Result<T> success(T info) {
return new Result<T>()
.setCode(ResultsCode.SUCCESS.code)
.setMsg(ResultsCode.SUCCESS.message)
.setInfo(info);
}
public static Result success() {
return new Result();
}
public static Result error() {
return error(ResultsCode.ERROR.message); // 输出定义好的errormessage
}
public static Result error(String message) { // 输出自己想输出的errormessage
return new Result()
.setCode(ResultsCode.ERROR)
.setMsg(message);
}
}
Result.java
:
package com.rds.study.pojo;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import java.io.Serializable;
import java.util.HashMap;
import java.util.Map;
@ApiModel
public class Result<T> implements Serializable {
private static final long serialVersionUID = 1L;
private final Map<String, Object> map = new HashMap<>();
@ApiModelProperty(value = "状态码")
public int code; // 状态码
@ApiModelProperty(value = "信息")
private String msg; // 信息
@ApiModelProperty(value = "对象")
private T info; // 对象
public Result(){
this.code = ResultsCode.SUCCESS.code;
this.msg = ResultsCode.SUCCESS.message;
}
public int getCode() {
return code;
}
public Result<T> setCode(int code) {
this.code = code;
return this;
}
public Result<T> setCode(ResultsCode resultsCode) {
this.code = resultsCode.code;
return this;
}
public String getMsg() {
return msg;
}
public Result<T> setMsg(String msg) {
this.msg = msg;
return this;
}
public Result<T> setMsg(ResultsCode resultsCode) {
this.msg = resultsCode.message;
return this;
}
public T getInfo() {
return info;
}
public Result<T> setInfo(T info) {
this.info = info;
return this;
}
public Result<T> putDataValue(String key, Object value) {
map.put(key, value);
this.info = (T) map;
return this;
}
@Override
public String toString() {
return "{" +
"code = " +
" , msg = " +
" , info = " +
info +
"}";
}
}
这样controller里方法返回成功后,直接return ResponseData.success(T)
即可
rds_blogs