一:内省是一种特殊的反射,来更方便的操作javaBean对象,通过内省可以获取到类字节码的描述器,

然后解剖每一个字段,获取每个字段的读写方法,即get/set方法的反射,然后获取或者是封装bean的value

下面是通过内省向Bean中set值得示例:

public static <T> T toBean(T t){
Class<?> clazz = t.getClass();
try {
//根据Class对象获取该类的BeanInfo信息
BeanInfo beanInfo = Introspector.getBeanInfo(clazz);
//根据BeanInfo获取该类中每一个字段的描述器
PropertyDescriptor[] props = beanInfo.getPropertyDescriptors();
//遍历描述器,获取每个字段的名称以及写方法(set方法),然后将value值set入bean中
for(PropertyDescriptor property:props){
String field = property.getName();
if(EXCLUDE_FIELD.equals(field)){
continue;
}
Method method = property.getWriteMethod();
method.invoke(t,getCode(field));
}
} catch (Exception e) {
e.printStackTrace();
}
return t;
}

整个测试案例如下:

 /**
*
*/
package com.hlcui.test; import java.beans.BeanInfo;
import java.beans.Introspector;
import java.beans.PropertyDescriptor;
import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Map; import com.hlcui.entity.Person; /**
* @author Administrator
*
*/
public class TestCase { public static Map<String,Object> codeMap = new HashMap<String,Object>(); private static final String EXCLUDE_FIELD = "class"; //静态代码块加载静态资源
static{
codeMap.put("id",1);
codeMap.put("name", "jack");
codeMap.put("salary",14000);
} public static void main(String[] args){
Person person = toBean(new Person());
System.out.println(person);
} public static <T> T toBean(T t){
Class<?> clazz = t.getClass();
try {
//根据Class对象获取该类的BeanInfo信息
BeanInfo beanInfo = Introspector.getBeanInfo(clazz);
//根据BeanInfo获取该类中每一个字段的描述器
PropertyDescriptor[] props = beanInfo.getPropertyDescriptors();
//遍历描述器,获取每个字段的名称以及写方法(set方法),然后将value值set入bean中
for(PropertyDescriptor property:props){
String field = property.getName();
if(EXCLUDE_FIELD.equals(field)){
continue;
}
Method method = property.getWriteMethod();
method.invoke(t,getCode(field));
}
} catch (Exception e) {
e.printStackTrace();
}
return t;
} public static Object getCode(String field){
return codeMap.get(field);
}
}

最新文章

  1. Linux安装gcc编译器详解
  2. Ubuntu主题美化--使用WPS风格
  3. ***RESTful API 设计指南(阮一峰)
  4. 简单的自绘CListBox,重载虚MeasureItem和DrawItem这两个虚函数
  5. 生成shadow中hash字串
  6. hdu-4419-Colourful Rectangle-段树区,并寻求
  7. 拖拽加点ui吧
  8. 海量数据挖掘MMDS week3:社交网络之社区检测:高级技巧
  9. QT中使用google breakpad捕获程序崩溃异常
  10. Httpclient发送json请求
  11. JS判断手机还是电脑访问网站
  12. 数字图像处理的Matlab实现(4)—灰度变换与空间滤波
  13. Servlet(1)—Servlet容器tomcat和HTTP协议
  14. Codeforces 1060E(思维+贡献法)
  15. C# 发送HTTP请求超时解决办法
  16. php深入学习
  17. Python中的import
  18. MongoDB: 聚集管道
  19. jQuery网格插件 ParamQuery
  20. 对于Android NDK编译器ARM和Thumb模式的理解

热门文章

  1. MapReduce教程(一)基于MapReduce框架开发&lt;转&gt;
  2. .net dll类库 生成chm说明文档
  3. Repeater 嵌套,子级Repeater获取 父级Repeater 中的值
  4. ie6幽灵文字及解决办法
  5. es 剩余磁盘空间达到es最小值,添加数据被block
  6. 微信小程序——购物车数字加减
  7. java android使用Gson解析泛型json数据
  8. JQuery之拖拽插件
  9. 【3】JVM-OutOfMemory异常重现
  10. (笔记)Linux内核中ioremap映射的透彻理解