1、使用枚举型定义常量
我们定义常量都是: public static final… ,现在使用枚举型定义。
public enum ResultCode {
SUCCESS(1, "请求成功"),
DEFAULT(0,"请求失败"),;
}
2、在枚举型添加方法
public enum ResultCode {
SUCCESS(1, "请求成功"),
DEFAULT(0,"请求失败"),;
private int code;
private String msg;
ResultCode(int code , String msg){
this.code = code;
this.msg = msg;
}
public int getCode() {
return code;
}
public void setCode(int code) {
this.code = code;
}
}
3、覆盖枚举型的方法
package com.zglt.customervoice.enumerate;
public enum ResultCode {
SUCCESS(1, "请求成功"),
DEFAULT(0,"请求失败"),;
private int code;
private String msg;
ResultCode(int code , String msg){
this.code = code;
this.msg = msg;
}
public int getCode() {
return code;
}
public void setCode(int code) {
this.code = code;
}
@Override
public String toString() {
return "ResultCode{" +
"code=" + code +
", msg='" + msg + '\'' +
'}';
}
}
4、实际运用枚举类
@RequestMapping("/unionCategory")
@ResponseBody
public RespEntity unionCategory(int parentId) {
//声明返回对象
RespEntity respEntity;
try {
//获取该类目下的子类目信息
List<Category> categoryList = categoryService.getCategoryByParentId(parentId);
respEntity = new RespEntity(ResultCode.SUCCESS);
respEntity.setData(categoryList);
log.info("获取类目信息成功,父类目ID:"+parentId+"\n所获得的子类目:"+categoryList);
return respEntity;
} catch (Exception e) {
respEntity = new RespEntity(ResultCode.DEFAULT);
respEntity.setMsg(RespMsg.CATEGORY_ERROR);
log.info("获取类目信息失败,父类目ID:"+parentId);
e.printStackTrace();
return respEntity;
//
}
}