记录:470
场景:Java中使用instanceof判断对象类型。例如在解析JSON字符串转换为指定类型时,先判断类型,再定向转换。在List<Object>中遍历Object时,先判断类型,再定向转换。
版本:JDK 1.8,Spring Boot 2.6.3。
一、解析Json字符串时,使用instanceof判断对象类型
场景:在基于微服务开发中,一个请求会贯穿多个微服务,一般在微服务之间传递参数均以JSON字符串为主流。
1.JSON字符串示例
{"getTime": "2023-08-13 17:50:12","getValue": ["13",350,193.62,37,"1813"]
}
解析:在getValue中传递参数,既有字符串、int型、double型等,在把JSON字符串时,无法转为指定类型,只能使用List<Object>类型是最合适。
需求:本例需求场景这些字符必须都转换为Double类型,再放到业务中使用。
2.使用instanceof判断对象类型
public static Double getDouble(Object obj) {if (obj == null) return null;Double result = null;try {if (obj instanceof Integer) {result = ((Integer) obj).doubleValue();} else if (obj instanceof Long) {result = ((Long) obj).doubleValue();} else if (obj instanceof Double) {result = (Double) obj;} else if (obj instanceof BigDecimal) {result = ((BigDecimal) obj).doubleValue();} else if (obj instanceof String) {result = Double.parseDouble((String) obj);}} catch (Exception e) {log.info("类型转换异常");e.printStackTrace();}return result;
}
3.测试示例
public static void f1() {String result = "{\n" +" \"getTime\": \"2023-08-13 17:50:12\",\n" +" \"getValue\": [\n" +" \"13\",\n" +" 350,\n" +" 193.62,\n" +" 37,\n" +" \"1813\"\n" +" ]\n" +"}";JSONObject jsonResult = (JSONObject) JSON.parse(result);List<Object> listResult = (List<Object>) jsonResult.get("getValue");List<Double> listResultD = new ArrayList<>();//类型转换listResult.forEach(item -> {listResultD.add(getDouble(item));});//遍历结果listResultD.forEach(item -> {System.out.println("" + item);});
}
4.输出结果
执行f1
13.0
350.0
193.62
37.0
1813.0
二、遍历List<Object>时,使用instanceof判断对象类型
场景:在接收到结果集List<Object>时,Object的具体类型由多个时,使用instanceof判断对象类型,再转换增强代码合理性。
1.使用instanceof判断对象类型
public static Double getDouble(Object obj) {if (obj == null) return null;Double result = null;try {if (obj instanceof Integer) {result = ((Integer) obj).doubleValue();} else if (obj instanceof Long) {result = ((Long) obj).doubleValue();} else if (obj instanceof Double) {result = (Double) obj;} else if (obj instanceof BigDecimal) {result = ((BigDecimal) obj).doubleValue();} else if (obj instanceof String) {result = Double.parseDouble((String) obj);}} catch (Exception e) {log.info("类型转换异常");e.printStackTrace();}return result;
}
2.测试示例
public static void f2() {List<Object> list01 = new ArrayList<>();Integer integerV = 813;Long longV = 209206L;Double doubleV = 209207.13D;BigDecimal bigDecimal01 = new BigDecimal("209208.23");BigDecimal bigDecimal02 = new BigDecimal("209209");String strV = "209210.35";list01.add(integerV);list01.add(longV);list01.add(doubleV);list01.add(bigDecimal01);list01.add(bigDecimal02);list01.add(strV);List<Double> list02 = new ArrayList<>();//类型转换list01.forEach(item -> {list02.add(getDouble(item));});//遍历结果list02.forEach(item -> {System.out.println("" + item);});
}
3.输出结果
执行f2
813.0
209206.0
209207.13
209208.23
209209.0
209210.35
以上,感谢。
2023年8月13日