泛型与string:http://blog.csdn.net/u013096088/article/details/69815631,http://blog.csdn.net/imzoer/article/details/8039369
当遇到如下所示的重载的时候,如果我现在传入一个字符串对象,我只想赋给data,不想赋给msg怎么办?
private ServerResponse(int status) { this.status = status; } //如果第二个参数不是string类型调用下面这个构造器 private ServerResponse(int status, T data) { this.status = status; this.data = data; } //如果第二个参数是string类型调用下面这个构造器 private ServerResponse(int status, String msg) { this.status = status; this.msg = msg; } private ServerResponse(int status, String msg, T data) { this.status = status; this.msg = msg; this.data = data; }
可以采用下面的对外开放public方法来解决,由于public方法已经定义好对应应该调用的构造方法,所以也就不会出现上面的问题。
//返回值是泛型<T>,传入0表示创建是成功的 public static <T> ServerResponse<T> createBySuccess() { return new ServerResponse<T>(ResponseCode.SUCCESS.getCode()); } //创建成功传入一个msg再返回 public static <T> ServerResponse<T> createBySuccessMessage(String msg) { return new ServerResponse<T>(ResponseCode.SUCCESS.getCode(), msg); } //创建成功传入data再返回 public static <T> ServerResponse<T> createBySuccess(T data) { return new ServerResponse<T>(ResponseCode.SUCCESS.getCode(), data); } //如果参数是string类型,但是应该把其赋给data而不是msg该怎么做? //调用下面的public方法同时传入msg和data即可 //创建成功传入一个msg和data再返回 public static <T> ServerResponse<T> createBySuccess(String msg, T data) { return new ServerResponse<T>(ResponseCode.SUCCESS.getCode(), msg, data); }
向外提供两个public方法来处理data本来就是string的情况。由于两个对外开放的方法名不同,所以很好区分。