标签:type time code class bean util keyset java对象 public
工作中遇到一个需求,根据对方返回Json来更新Java对象。查阅资料,写了个工具类,同时学到了反射获取集合泛型类型。代码里json类库为fastjson
1 public class JsonUtil { 2 3 /** 4 * JavaBean的属性比Json多时,根据Json更新JavaBean同名字段的值 5 * 6 * @param bean 7 * @param json 8 * @param <T> 9 */ 10 public static <T> void patchUpdate(T bean, JSONObject json) throws Exception { 11 Set<String> keys = json.keySet(); 12 Field[] fields = bean.getClass().getDeclaredFields(); 13 for (String key : keys) { 14 for (Field field : fields) { 15 if (field.getName().equals(key)) { 16 String value = json.getString(key); 17 String type = field.getType().toString(); 18 field.setAccessible(true); 19 if (type.endsWith("String")) { 20 field.set(bean, value); 21 } else if (type.endsWith("int")) { 22 field.set(bean, Integer.parseInt(value)); 23 } else if (type.endsWith("double")) { 24 field.set(bean, Double.parseDouble(value)); 25 } else if (type.endsWith("Date")) { 26 DateFormat fmtDateTime = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); 27 Date date = fmtDateTime.parse(value); 28 field.set(bean, date); 29 } else if (type.endsWith("List")) { 30 //先获取List的类型:java.util.List<E> 31 ParameterizedType pt = (ParameterizedType)field.getGenericType(); 32 //获取泛型:E 33 Class e = (Class)pt.getActualTypeArguments()[0]; 34 List list = JSONArray.parseArray(value, e); 35 field.set(bean, list); 36 } 37 } 38 } 39 } 40 } 41 }
标签:type time code class bean util keyset java对象 public
原文地址:http://www.cnblogs.com/hephae/p/6947654.html