泛型方法的使用笔记,持续修改,完善

 1 package com.mmall.common;
 2 
 3 import org.codehaus.jackson.annotate.JsonIgnore;
 4 import org.codehaus.jackson.map.annotate.JsonSerialize;
 5 
 6 import java.io.Serializable;
 7 
 8 /**
 9  * @author chd
10  * @version 1.0
11  * @description 
12  * @date 2018/6/3
13  */
14 @JsonSerialize(include =  JsonSerialize.Inclusion.NON_NULL)
15 //保证序列化json的时候,如果是null的对象,key也会消失
16 public class ServerResponse<T> implements Serializable {
17 
18     private int status;
19     private String msg;
20     private T data;
21 
22 
23     private ServerResponse(int status){
24         this.status = status;
25     }
26 
27     private ServerResponse(int status, T data){
28         this.status = status;
29         this.data = data;
30     }
31 
32     private ServerResponse(int status, String msg){
33         this.status = status;
34         this.msg = msg;
35     }
36 
37     private ServerResponse(int status, String msg, T data) {
38         this.status = status;
39         this.msg = msg;
40         this.data = data;
41     }
42 
43     @JsonIgnore
44     //使之不在json序列化结果当中
45     public boolean isSuccess(){
46         return this.status == ResponseCode.SUCCESS.getCode();
47     }
48 
49     public int getStatus(){
50         return status;
51     }
52     public T getData(){
53         return data;
54     }
55     public String getMsg(){
56         return msg;
57     }
58 
59 
60     public static <T> ServerResponse<T> createBySuccess(){
61         return new ServerResponse<T>(ResponseCode.SUCCESS.getCode());
62     }
63     //<T> ServerResponse<T>对于这个想了很久,也看了老师的解释,个人理解为: 
    public static ServerResponse<T> createBySuccess(){}不加第一个是声明了一个方法,一个有泛型作为返回值的函数方法,
    然后加上第一个<T>是说声明此方法持有一个类型T,也可以理解成,将此方法声明为泛型方法,第一个记住是持有的意思,如果不持有,
    后面的Serv<T>会报错
64 65 public static <T> ServerResponse<T> createBySuccessMessage(String msg){ 66 return new ServerResponse<T>(ResponseCode.SUCCESS.getCode(),msg); 67 } 68 69 public static <T> ServerResponse<T> createBySuccess(T data){ 70 return new ServerResponse<T>(ResponseCode.SUCCESS.getCode(),data); 71 } 72 73 public static <T> ServerResponse<T> createBySuccess(String msg,T data){ 74 return new ServerResponse<T>(ResponseCode.SUCCESS.getCode(),msg,data); 75 } 76 77 78 public static <T> ServerResponse<T> createByError(){ 79 return new ServerResponse<T>(ResponseCode.ERROR.getCode(),ResponseCode.ERROR.getDesc()); 80 } 81 82 83 public static <T> ServerResponse<T> createByErrorMessage(String errorMessage){ 84 return new ServerResponse<T>(ResponseCode.ERROR.getCode(),errorMessage); 85 } 86 87 public static <T> ServerResponse<T> createByErrorCodeMessage(int errorCode,String errorMessage){ 88 return new ServerResponse<T>(errorCode,errorMessage); 89 } 90 }

以上class类适用于服务器返回json字符串给前端的通用返回泛型类,仅此谨记泛型使用。

posted on 2018-06-05 10:17  EastChilde  阅读(443)  评论(0编辑  收藏  举报

导航