1.给定一个实参,以及期望类型
private <T> T getValueByClass(Object obj, Class<T> cs) { String obj2 = String.valueOf(obj); Object obj3; if (cs.equals(String.class)) { obj3 = obj2; } else if (cs.equals(int.class) || cs.equals(Integer.class)) { obj3 = Integer.valueOf(obj2); } else if (cs.equals(long.class) || cs.equals(Long.class)) { obj3 = Long.valueOf(obj2); } else if (cs.equals(short.class) || cs.equals(Short.class)) { obj3 = Short.valueOf(obj2); } else if (cs.equals(byte.class) || cs.equals(Byte.class)) { obj3 = Byte.valueOf(obj2); } else if (cs.equals(float.class) || cs.equals(Float.class)) { obj3 = Float.valueOf(obj2); } else if (cs.equals(double.class) || cs.equals(Double.class)) { obj3 = Double.valueOf(obj2); } else if (cs.equals(boolean.class) || cs.equals(Boolean.class)) { obj3 = Boolean.valueOf(obj2); } else if (cs.equals(Date.class)) { obj3 = new Date(Long.parseLong(obj2)); } else { obj3 = (T) obj; } return (T) obj3; }
2.实际调用
private ClientUserAssist filter(SoMap clientUserMap, Map<String, String> link) { ClientUserAssist clientUserAssist = new ClientUserAssist(); for (Field field : clientUserAssist.getClass().getDeclaredFields()) { try { Object value = clientUserMap.get(link.get(field.getName())); if (value == null) { continue; } field.setAccessible(true); Object valueConvert = getValueByClass(value, field.getType()); field.set(clientUserAssist, valueConvert); } catch (IllegalArgumentException | IllegalAccessException e) { throw new RuntimeException("属性取值出错:" + field.getName(), e); } } return clientUserAssist; }
标签:反射,obj3,obj2,将值,equals,else,特定,cs,class From: https://www.cnblogs.com/upupup-999/p/17587108.html