Java Spring Boot如何让gameId列表同时兼容可转Int与普通字符串?
解决方案
是否需要取消gameId转Int的逻辑,完全取决于你的业务场景,下面提供两种可落地的调整方案:
方案1:保留gameId转Int逻辑,仅过滤非法值(适用于业务仅需要合法数字gameId的场景)
不需要抛出异常,只需要把无法转为Int的字符串过滤掉即可,同时修正原代码中两处编译问题:遗漏lines属性赋值、不存在的requestId参数引用,调整后的代码如下:
import java.util.ArrayList; import java.util.List; class SomeConstructorClass { final Integer lines; final List<Integer> gameIdList; // 若业务不需要requestId可直接删除该属性和相关赋值、参数代码 final String requestId; SomeConstructorClass( Integer lines, String requestId, List<String> gameIdList) { Validation.notNull(lines, "lines can not be null"); // 补充lines属性赋值 this.lines = lines; this.requestId = requestId; Validation.notEmpty(gameIdList, "gameIdList can not be empty"); List<Integer> tempGameIds = new ArrayList<>(); for (String gameId : gameIdList){ // 删除原断言抛错逻辑,仅将合法的数字id加入列表 if (isInt(gameId)) { tempGameIds.add(Integer.valueOf(gameId)); } } // 若业务要求过滤后列表不能空,可在此处加校验: // Validation.notEmpty(tempGameIds, "不存在合法的gameId"); this.gameIdList = tempGameIds; } private static boolean isInt(String string){ if (string == null) { return false; } try { Integer.parseInt(string); } catch (NumberFormatException e) { return false; } return true; } }
方案2:取消gameId转Int逻辑,保留原始字符串(适用于业务需要保留所有gameId原始值的场景)
直接把存储gameId的列表类型改为String即可,不需要做类型转换:
import java.util.List; class SomeConstructorClass { final Integer lines; final List<String> gameIdList; final String requestId; SomeConstructorClass( Integer lines, String requestId, List<String> gameIdList) { Validation.notNull(lines, "lines can not be null"); this.lines = lines; this.requestId = requestId; Validation.notEmpty(gameIdList, "gameIdList can not be empty"); // 不需要转换直接赋值 this.gameIdList = gameIdList; } }
内容的提问来源于stack exchange,提问作者user9347049
相关产品推荐
相关产品推荐

