HttpResp类:
code,msg,result,time
应用
code —— 映射 ———- msg
{code:200,msg:’success’} ——————-json
定义已知常量
接口控制常量
枚举类型enum
常量的可读性问题,switch 用枚举较多,框架等
枚举本质上是什么?
是一个不能继承的类,里面都是不可变常量!!!
public final class Weather extends java.lang.Enum<Weather> {
public static final Weather SUN;
public static final Weather RAINING;
public static final Weather CLOUDY;
public static Weather[] values();
public static Weather valueOf(java.lang.String);
static {};
}
code和msg绑定
400——ERROR
200——SUCCESS
@Getter
public enum RespCode {
SUCCESS(200,"访问成功"),
AUTHORITY_ERROR(401,"权限不足"),
API_REFUSED(409,"接口拒绝访问"),
ERROR(400," 访问失败");
int code;
String msg;
RespCode(int code, String msg){
this.code= code;
this.msg = msg;
}
}
private
protected : 继承或者同包
default(默认,省略)
public
HttpResp类下写泛型方法
@Data
@NoArgsConstructor
@AllArgsConstructor
public class HttpResp<T> {
private Integer code;
private String msg;
private T result;
private LocalDate time;
public static <T> HttpResp<T> success(T result){
RespCode resp = RespCode.SUCCESS;
return new HttpResp<T>(
resp.getCode(),
resp.getMsg(),
result,
LocalDate.now()
);
}
public static <T> HttpResp<T> error(){
RespCode resp = RespCode.ERROR;
return new HttpResp<T>(
resp.getCode(),
resp.getMsg(),
null,
LocalDate.now()
);
}
}