java 内省机制

什么是内省:

官方:
内省(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 ,只分享干货!

可以关注下博主的公众号,实时推送解决方案!
公众号

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值