根据jsonobject中的部分数据更新javabean中对应的属性[PATCH]
发布时间:2020-12-16 18:56:03 所属栏目:百科 来源:网络整理
导读:springmvc restful api中的patch方法中使用到的一个类分享给筒子们: 欢迎批评指正 import java.lang.reflect.Field;import java.util.Iterator;import net.sf.json.JSONObject;public class JavaBeanUtils {/** * 根据json中的部分数据更新bean中对应的属性
springmvc restful api中的patch方法中使用到的一个类分享给筒子们: 欢迎批评指正 import java.lang.reflect.Field; import java.util.Iterator; import net.sf.json.JSONObject; public class JavaBeanUtils { /** * 根据json中的部分数据更新bean中对应的属性 * @param bean * @param json * @return * @throws Exception */ public static <T> void patch(T bean,JSONObject json) throws Exception{ Field[] fields=bean.getClass().getDeclaredFields(); for(Field field:fields){ // System.out.println(field.getName()); Iterator iterator = json.keys(); while(iterator.hasNext()){ String key = (String) iterator.next(); if(field.getName().equals(key)){ String value = json.getString(key); String type = field.getType().toString();//得到此属性的类型 field.setAccessible(true);//设置些属性是可以访问的 // 赋值(目前只判断了以下几种,如有其他的请自行扩展) if (type.endsWith("String")) { field.set(bean,value); }else if(type.endsWith("float")){ field.set(bean,Float.valueOf(value)); }else if(type.endsWith("int")){ field.set(bean,Integer.parseInt(value)); } } } } } } 获取属性的相关说明: http://www.52php.cn/article/p-wfxuojyr-es.html getFields()获得某个类的所有的公共(public)的字段,包括父类。 其他实现: xxxx source = new xxxx(); Method[] sourceMethods = source.getClass().getMethods(); for(int i=0;i<sourceMethods.length;i++){ if(sourceMethods[i].getName().startsWith("get")){ lsName = sourceMethods[i].getName().substring(3); // 属性 Object loValue = sourceMethods[i].invoke(source,null); // 值 String lsSourceType = sourceMethods[i].getReturnType().getName(); //类型 } } 参考:http://www.52php.cn/article/p-dgymtvfj-no.html http://blog.sina.com.cn/s/blog_3c62c21f01011xci.html (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |