java使用枚举类统一返回值result
编写Result类
public class Result<T> {
private Integer code;
private String msg;
private T data;
public Result(Integer code, String msg, T data) {
this.code = code;
this.msg = msg;
this.data = data;
}
public Integer getCode() {
return code;
}
public void setCode(Integer code) {
this.code = code;
}
public String getMsg() {
return msg;
}
public void setMsg(String msg) {
this.msg = msg;
}
public T getData() {
return data;
}
public void setData(T data) {
this.data = data;
}
@Override
public String toString() {
return "Result{" +
"code=" + code +
", msg='" + msg + '\'' +
", data=" + data +
'}';
}
}
创建枚举类ResultCode
public enum ResultCodeEnum {
SUCCESS(200,"操作成功"),
ERROR(201,"操作失败"),
SEARCH_ERROR(202,"查询异常"),
CHECK_ERROR(400,"校验异常"),
OPERATION_ERROR(500,"请联系开发人员")
;
/**
* 返回的状态码
*/
private int code ;
/**
* 返回状态码对应的信息
*/
private String msg;
ResultCodeEnum(int code, String msg) {
this.code = code;
this.msg = msg;
}
public int getCode() {
return code;
}
public String getMsg() {
return msg;
}
public static ResultCodeEnum find(int code){
for (ResultCodeEnum resultCodeEnum : ResultCodeEnum.values()) {
if(resultCodeEnum.getCode() == code){
return resultCodeEnum;
}
}
return null;
}
public static void main(String[] args) {
System.out.println(find(201).getMsg());
}
}