1泛型的好处:
1把运行时的错误,提前到编译时
2无需强转
3健壮性,复用
创建一个空接口便于扩展
/**
* 响应接口定义(方便使用泛型扩展旧的响应体类型,比如可能有多个类型的响应结构体)
*
*/
public interface IVideoCmdAck {
}
//旧的响应结构体
public class CMDVideoAck implements IVideoCmdAck {
private String msgType;
private String param1;
private String param2;
private String errorCode;
private String errorMsg;
private String token;
private String clientID;
private String sessionID;
public CMDVideoAck() {
}
public CMDVideoAck(String _msgType, String _param1, String _param2) {
msgType = _msgType;
param1 = _param1;
param2 = _param2;
}
public String getMsgType() {
return msgType;
}
public void setMsgType(String _msgType) {
msgType = _msgType;
}
public String getParam1() {
return param1;
}
public void setParam1(String _param1) {
param1 = _param1;
}
public String getParam2() {
return param2;
}
public void setParam2(String _param2) {
param2 = _param2;
}
public String getErrorCode() {
return errorCode;
}
public void setErrorCode(String errorCode) {
this.errorCode = errorCode;
}
public String getErrorMsg() {
return errorMsg;
}
public void setErrorMsg(String errorMsg) {
this.errorMsg = errorMsg;
}
public String getToken() {
return token;
}
public void setToken(String token) {
this.token = token;
}
public String getClientID() {
return clientID;
}
public void setClientID(String clientID) {
this.clientID = clientID;
}
public String getSessionID() {
return sessionID;
}
public void setSessionID(String sessionID) {
this.sessionID = sessionID;
}
@Override
public String toString() {
return "CMDVideoAck{" +
"msgType='" + msgType + '\'' +
", param1='" + param1 + '\'' +
", param2='" + param2 + '\'' +
", errorCode='" + errorCode + '\'' +
", errorMsg='" + errorMsg + '\'' +
", token='" + token + '\'' +
", clientID='" + clientID + '\'' +
", sessionID='" + sessionID + '\'' +
'}';
}
}
/**
* 转换为旧回应
*
* @param hisenseVideoCmdAck
* @param <T>
* @return
*/
public static <T extends IVideoCmdAck> T map(HisenseVideoCmdAck hisenseVideoCmdAck) {
T videoCmdAck;
switch (hisenseVideoCmdAck.getMsgType()) {
//注册
case "register": {
//TODO 部分参数缺失
videoCmdAck = transform(hisenseVideoCmdAck.getMsgType(), String.valueOf(hisenseVideoCmdAck.getCode()),
hisenseVideoCmdAck.getMessage(), null,
null, (String) hisenseVideoCmdAck.getData().get("token"),
"0", null);
Log.e(TAG,"receive=>"+ JSON.toJSONString(hisenseVideoCmdAck));
break;
}
case "createRoom": {
//TODO 响应数据转换
videoCmdAck = transform(hisenseVideoCmdAck.getMsgType(), String.valueOf(hisenseVideoCmdAck.getCode()),
hisenseVideoCmdAck.getMessage(), null,
null, null,
null, null);
Log.e(TAG,"createRoom receive=>"+ JSON.toJSONString(hisenseVideoCmdAck));
break;
}
//默认为空
default:
videoCmdAck = null;
break;
}
return videoCmdAck;
}