需求
json字符串(string)->reflect.type,无法知道是否为基本类型。
步骤
- 判断是type是否为初始类型
public static boolean isPrimitiveType(Type type) {
Class<?> typeClz = (Class<?>) type;
return Stream.of(String.class, Integer.class, Double.class, Float.class,
Long.class, Boolean.class, Byte.class, Character.class)
.anyMatch(clz -> clz.isAssignableFrom(typeClz));
}
- 如果是初始类型的话,那么转化为初始类型
public static Object transferPrimitiveType(String value, Type type) {
Class<?> typeClz = (Class<?>) type;
try {
Constructor<?> constructor = typeClz.getConstructor(String.class);
constructor.setAccessible(true);
Object instance = constructor.newInstance(value);
constructor.setAccessible(false);
return instance;
} catch (NoSuchMethodException | InstantiationException | IllegalAccessException | InvocationTargetException e) {
throw new RuntimeException("json parse value failed ", e);
}
}
- 如果不是初始类型,那么正常的转化
BbgConstant.OM.readValue(body, BbgConstant.OM.getTypeFactory().constructType(type));