根据jsonobject中的部分数据更新javabean中对应的属性[PATCH]
2016-07-24 15:34
1056 查看
springmvc restful api中的patch方法中使用到的一个类分享给筒子们:
欢迎批评指正
获取属性的相关说明:http://blog.csdn.net/sxbjffsg163/article/details/9955701
getFields()获得某个类的所有的公共(public)的字段,包括父类。
getDeclaredFields()获得某个类的所有申明的字段,即包括public、private和proteced,但是不包括父类的申明字段。
同样类似的还有getConstructors()和getDeclaredConstructors(),getMethods()和getDeclaredMethods()。
其他实现:
参考:http://blog.csdn.net/restraint/article/details/17951453
http://blog.sina.com.cn/s/blog_3c62c21f01011xci.html
欢迎批评指正
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://blog.csdn.net/sxbjffsg163/article/details/9955701
getFields()获得某个类的所有的公共(public)的字段,包括父类。
getDeclaredFields()获得某个类的所有申明的字段,即包括public、private和proteced,但是不包括父类的申明字段。
同样类似的还有getConstructors()和getDeclaredConstructors(),getMethods()和getDeclaredMethods()。
其他实现:
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://blog.csdn.net/restraint/article/details/17951453
http://blog.sina.com.cn/s/blog_3c62c21f01011xci.html
相关文章推荐
- PHP5.2.*防止Hash冲突拒绝服务攻击的Patch
- patch 的用法
- Oracle 数据库Patch概念性小常识 PSU,CPU,bundle patch
- java patch补丁文件的结构
- How many times rampant Warcraft Star players ah
- Ubuntu 内核编译
- Mathcad patch
- 欺骗的艺术----(9)
- 一些比较生僻的 RPM 命令
- Jbuild2005安装
- rdesktop研究随笔
- office2003无法正常安装卸载问题解决
- 在WinCE5.0和WinCE6.0下,编译选项介绍
- [转]程序员的素养
- 又到了考评的时候
- 用access-list 对抗“冲击波”病毒
- CVS大全
- 在AS4上架设Cacti 0.8.6g
- git使用说明
- MPlayer-1.0pre6a的Bug和相应的patch