Java 静态方法的返回值泛型使用与调用 static method generic return type and invoke

泛型(generic)类型在 Java 中使用特别频繁, 尤其在各种集合类(Collection)中. 一般如果自定义的类要使用泛型, 那么需要在类定义的时候, 声明泛型, 如:

public class MyClass<T> {...}

那么, 如果想在类的静态方法里上使用泛型, 以及如何在调用的时候, 传入泛型类型呢?

  1. 静态方法上在 static 关键字之后, 声明泛型:
public static <R> Builder<R> builder() {...}
  1. 调用静态方法在.之后, 方法之前:
MyResponse.<MyReturnType>builder().status(0).result(new MyReturnType()).build();

比如, 我们在各种 API 经常用的这类返回结果的类:

public class ApiResponse<T> {

    public static <R> Builder<R> builder() {
        return new ApiResponse.Builder<R>();
    }
    
    public ApiResponse(int status) {
        super();
        this.status = status;
    }

    public ApiResponse(int status, T result) {
        super();
        this.status = status;
        this.result = result;
    }

    private int status;//0 is success, others are all 
    
    private String errCode;
    private String errMsg;
    
    private T result;

    public int getStatus() {
        return status;
    }

    public void setStatus(int status) {
        this.status = status;
    }

    public String getErrCode() {
        return errCode;
    }

    public void setErrCode(String errCode) {
        this.errCode = errCode;
    }

    public String getErrMsg() {
        return errMsg;
    }

    public void setErrMsg(String errMsg) {
        this.errMsg = errMsg;
    }

    public Object getResult() {
        return result;
    }

    public void setResult(T result) {
        this.result = result;
    }
    
    static class Builder<T> {
        private int status;//0 is success, others are all 
        private String errCode;
        private String errMsg;
        private T result;
        
        public Builder<T> status(int status) {
            this.status = status;
            return this;
        }
        
        public Builder<T> errCode(String errCode) {
            this.errCode = errCode;
            return this;
        }
        
        public Builder<T> errMsg(String errMsg) {
            this.errMsg = errMsg;
            return this;
        }
        
        public Builder<T> result(T result) {
            this.result = result;
            return this;
        }
        
        public ApiResponse<T> build() {
            ApiResponse<T> rsps  = new ApiResponse<T>(status, result);
            rsps.setErrCode(errCode);
            rsps.setErrMsg(errMsg);
            return rsps;
        }
    }
}

标签: none

添加新评论