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