直接上代码
1.定义自己所需要的返回值类型
public class CodeMsg implements Cloneable {
private int retCode;
private String message;
// 通用异常
public static CodeMsg SUCCESS = new CodeMsg(0, "success");
public static CodeMsg EMPTY_PARAM_ERROR = new CodeMsg(400, "参数为空");
public static CodeMsg INTER_ERROR = new CodeMsg(505, "服务端异常");
private CodeMsg(int retCode, String message) {
this.retCode = retCode;
this.message = message;
}
public int getRetCode() {
return retCode;
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
@Override
protected Object clone() throws CloneNotSupportedException {
return (CodeMsg) super.clone();
}
}
2.返回值的封装
package com.ystx.common;
public class Result<T> {
private String message;
private int retCode;
private T data;
private Result(T data) {
this.retCode = 200;
this.message = "成功";
this.data = data;
}
private Result(CodeMsg cm) {
if (cm == null) {
return;
}
this.retCode = cm.getRetCode();
this.message = cm.getMessage();
}
/**
* 成功时候的调用
*
* @return
*/
public static <T> Result<T> success(T data) {
return new Result<T>(data);
}
/**
* 成功,不需要传入参数
*
* @return
*/
@SuppressWarnings("unchecked")
public static <T> Result<T> success() {
return (Result<T>) success("");
}
/**
* 失败时候的调用
*
* @return
*/
public static <T> Result<T> error(CodeMsg cm) {
return new Result<T>(cm);
}
/**
* 失败时候的调用,扩展消息参数
*
* @param cm
* @param msg
* @return
*/
public static <T> Result<T> error(CodeMsg cm, String msg) {
CodeMsg newCodeMsg = null;
try {
newCodeMsg = (CodeMsg) cm.clone();
} catch (Exception e) {
e.printStackTrace();
}
newCodeMsg.setMessage(cm.getMessage() + "--" + msg);
return new Result<T>(newCodeMsg);
}
public T getData() {
return data;
}
public String getMessage() {
return message;
}
public int getRetCode() {
return retCode;
}
}
网友评论