Java泛型:利用泛型動態確認方法返回值類型

根據泛型類型動態返回對象

public <T extends PackObject> T  unPackMessage(String interfaceCode, String respValue, Class<T>  clazz, String sysType) throws IOException {
    log.info(">> unPackMessage start, interfaceCode is {}, respValue is {}", interfaceCode, respValue);
    Map<String, Object> result = null;
    // get pack_convert.prop file content
    PackConvertMessage packConvertMessage = getPackConvertFileContent();
    String func = packConvertMessage.getInterfaceMapping().get(interfaceCode);
    if (StringUtils.isBlank(func)){
        log.error("<< unPackMessage error, No response message with current interface configured");
        return null;
    }
    String respSerialNumber = packConvertMessage.getRespFuncMapping().get(func);
    String currPackType = PackConvertConstant.SystermType.CLIENT.equals(sysType) ? client_pack_type : pack_type;
    switch (currPackType){
        case PackConvertConstant.PackType.NON_FIXED_LENGTH:
            result = unpackNoFixedMessage(respValue, connect_char, respSerialNumber, PACK_CONVERT_FILE_MAPPING_SEPARATOR, sysType);
            break;
        case  PackConvertConstant.PackType.FIXED_LENGTH:
            result = unpackFixedMessage(respValue, respSerialNumber, PACK_CONVERT_FILE_MAPPING_SEPARATOR);
            break;
        case  PackConvertConstant.PackType.XML:
            result = unpackXmlMessage(respValue, respSerialNumber, PACK_CONVERT_FILE_MAPPING_SEPARATOR);
            break;
        case PackConvertConstant.PackType.JSON:
            result = unpackJsonMessage(respValue, respSerialNumber);
            break;
    }
    log.info("<< unPackMessage success, return value is {}", JSON.toJSONString(result));
    T t = JSON.toJavaObject(JSON.parseObject(JSON.toJSONString(result)), clazz);
    return t;
}

根據泛型類型動態返回集合

 public <E extends BaseLiquidation, T extends BaseLiquidation> List<E> convertFileToObj(String localFilePath, Class<E> clazz, Class<T> tclazz) throws IOException, NoSuchMethodException, IllegalAccessException, InstantiationException {
     logger.info(">> convertFileToObj, localFilePath is {}, clazz is {}", localFilePath, clazz.getName());
     BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream(localFilePath),"utf-8"));
     StringBuilder sb = new StringBuilder();
     String line;
     while ((line = br.readLine()) != null){
         sb.append(line);
         sb.append(System.getProperty("line.separator"));
     }
     List<E> result = messageToObj(sb.toString(), clazz);
     logger.info("<< convertFileToObj end");
     return result;
}

 

public <E extends BaseLiquidation> List<E> convertFileToObj(String localFilePath, Class<E> clazz) throws IOException, NoSuchMethodException, IllegalAccessException, InstantiationException {
    logger.info(">> convertFileToObj, localFilePath is {}, clazz is {}", localFilePath, clazz.getName());
    BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream(localFilePath),"utf-8"));
    StringBuilder sb = new StringBuilder();
    String line;
    while ((line = br.readLine()) != null){
        sb.append(line);
        sb.append(System.getProperty("line.separator"));
    }
    List<E> result = messageToObj(sb.toString(), clazz);
    logger.info("<< convertFileToObj end");
    return result;
}

泛型方法基本介紹

  • public與返回值中間的<T>很是重要,表示此方法聲明爲泛型方法
  • 只有聲明瞭<T>的方法纔是泛型方法,泛型類中使用了泛型的成員方法並不能算是泛型方法
  • <T>代表該方法將使用泛型類型T,此時才能夠在方法中使用泛型類型T
  • 與泛型類的定義同樣,T能夠隨便寫成任意標識,好比T、E、K、V、S等

泛型限制上下邊界

  • 泛型限制上邊界:傳入的類型只能是指定類的子類,好比Class<? extend PackObject>
  • 泛型限制下邊界:傳入的類型只能是指定類的父類,好比DiagnosticListener<? super JavaFileObject>

另外附經常使用泛型標識說明

  • 常見的一些泛型標識就是T(類型)、E(元素)、K(key)、V(value)、?(通配符,不肯定的)這幾個,其實填任何字母都行
相關文章
相關標籤/搜索