
内省:将javabean中不管是公有地还是私有的,通过构造器,将其中的属性和方法拿出来使用.
底层原理:通过反射来实现.
通过BeanInfo来获取bean中的属性,方法,并操控
public void copybean(Mapmap, Object bean){ try { //获取javabean BeanInfo beanInfo = Introspector.getBeanInfo(bean.getClass(),Object.class); //获取所有属性 PropertyDescriptor[] propertyDescriptor = beanInfo.getPropertyDescriptors(); //如果实体类中属性为空,则不做任何操作 if (propertyDescriptor==null){ return; } //遍历所有属性 for (PropertyDescriptor p:propertyDescriptor) { //获取集合中属性的值 String value = map.get(p.getName()); //如果值为空或者为空字符串,则跳过当前循环进入下一次 if (value==null||value.trim().equals("")){ continue; } //将所有属性set到bean中 //为p设置set方法,getReadMethod()为声明的变量设置get方法 Method writeMethod = p.getWriteMethod(); System.out.println(p.getPropertyType().getName()); System.out.println(Integer.class.getName()); //获取属性的类型 if (p.getPropertyType().getName().equals("int")){ //判断类型是否为Integer类型 writeMethod.invoke(bean,Integer.parseInt(value)); }else if (p.getPropertyType().getName().equals(Double.class.getName())){ //判断类型是否为Double类型 writeMethod.invoke(bean,Double.valueOf(value)); }else { writeMethod.invoke(bean,value); } } }catch (Exception e){ e.printStackTrace(); throw new RuntimeException(); } }