我们在封装方法的时候,有的时候除了需要返回数据结果集data,有的时候需要返回code(或者status) 或者 msg ,
此时可以采取下面两种方式进行封装方法的返回值:
一.返回结果使用HashMap接收
1.方法中的数据封装到hashmap中
public Map<String,Object> result(Object object)
{
Map<String,Object> result = new HashMap<String, Object>();
result.put("status", "1");
result.put("msg", "成功");
if(条件1不通过校验)
{
result.put("status", "-1");
result.put("msg", "....");
return result;
}
if(条件2不通过校验)
{
result.put("status", "-1");
result.put("msg", "....");
return result;
}
//封装返回数据
Object data = new Object();
result.put("data", data);
return result;
}
======================================================================
2.方法调用:
public void test()
{
Map<String,Object> result = this.result(new Object());
if(!"1".equals(result.get("status").toString()))
{
//校验不通过
return;
}else
{
//如果校验通过,拿到数据
Object data = result.get("data");
//TODO
}
}
================================================================================================
二.使用泛型对象接收
1.通用结果集封装
public class Result<T>
{
private static final String SUCCESS = "1";
private static final String FAIL = "0";
private String code;
private String msg;
private T Data;
public Result(String code)
{
this.code = code;
}
public Result(String code, String msg)
{
super();
this.code = code;
this.msg = msg;
}
public Result(String code, String msg, T data)
{
super();
this.code = code;
this.msg = msg;
Data = data;
}
public String getCode()
{
return code;
}
public void setCode(String 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)
{
Data = data;
}
public static <T> Result<T> ok(T object)
{
return new Result<T>(SUCCESS, "", object);
}
public static <T> Result<T> ok()
{
return new Result<T>(SUCCESS);
}
public static <T> Result<T> nok(String msg)
{
return new Result<T>(FAIL, msg);
}
public static <T> Result<T> nok()
{
return new Result<T>(FAIL);
}
public static <T> Result<T> nok(String code, String msg)
{
return new Result<T>(code, msg);
}
public static <T> Result<T> nok(String code, String msg, T object)
{
return new Result<T>(code, msg, object);
}
public boolean isOk()
{
return Result.equals(getCode());
}
}
=============================================================================
2.对应需要返回数据T data 的 方法
public Result<T> result (Object object)
{
if(条件1不通过校验)
{
return Result.nok("。。。");;
}
if(条件2不通过校验)
{
return Result.nok("。。。");;
}
return Result.ok(T);
}
=============================================================================
3.方法调用:
public void test
{
Result<T> result = this.result(object);
if(!result.isOk())
{
//校验不通过
return;
}else
{
//如果校验通过,拿到数据
Object data = result.getData();
//TODO
}
}