什么是内省:
官方:
内省(Introspector)是Java语言对Bean类属性、事件的一种缺省处理方法。
个人理解:
说白了就是通过反射获取javabean的setting方法并通过method执行
内省的两种实现方式:
1.通过Introspector接口获取PropertyDescriptor(实现类)实现
2.通过PropertyDescriptor(实现类)实现
案例1 :通过Introspector
BeanInfo beanInfo = Introspector.getBeanInfo(Student.class);
PropertyDescriptor[] propertyDescriptors = beanInfo.getPropertyDescriptors();
注意:此种方式的PropertyDescriptor返回的是多个,javabean中有几对getter,setter方法就有几个PropertyDescriptor,此时还包含父类的setter和getter,(默认object里的getClass方法也算)
案例2 :通过PropertyDescriptor
Student student=new Student();
Map<String, Object> properties =new HashMap<>();
properties.put("username", "池永福");
properties.put("studyTime", "2017-9-20 5:12:54");
ConvertUtils.register(new DateLocaleConverter(), Date.class);
BeanUtils.populate(student, properties);
System.out.println(student);
ConvertUtils.register原理实现
Student student=new Student();
Map<String, Object> properties =new HashMap<>();
properties.put("username", "池永福");
properties.put("studyTime", "2017-9-20 5:12:54");
Converter converter =new Converter() {
//首先底层实现是先找到setter属性的类型(也是返回值),发现
//类型和需要注入的属性值不匹配时,抛出异常,此时就需要通过ConvertUtils
//注册一个类型转换
@Override //参数1: 属性的类型 参数2:需要注入的值
public Object convert(Class type, Object value) {
SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
if(value instanceof String) {
String val=(String)value;
try {
return sdf.parse(val);
} catch (ParseException e) {
throw new RuntimeException(e);
}
}
return null;
}
};
ConvertUtils.register(converter , Date.class);
BeanUtils.populate(student, properties);
System.out.println(student);
个人博客 www.yunsuibi ,只分享干货!
可以关注下博主的公众号,实时推送解决方案!