标签:des 对象 val 实例 elements eva gets 变量 tty
public void fun2() throws Exception { //通过反射和dom4j实例化id=stu1的对象,并输出 SAXReader reader = new SAXReader(); Document document = reader.read(this.getClass().getResourceAsStream("/beans.xml")); String xpath="/beans/bean[@id=\"stu1\"]"; Element element=(Element) document.selectSingleNode(xpath); Class clazz=Class.forName(element.attributeValue("className")); Student student=(Student) clazz.newInstance(); List<Element> els=element.elements(); System.out.println(student); //根据变量名获取变量类型 2"); for (Element e : els) { Field f=clazz.getDeclaredField(e.attributeValue("name")); String sClassString=f.getType().getName(); Method method=clazz.getMethod("set"+captureName(f.getName()),Class.forName(sClassString)); method.invoke(student, e.attributeValue("value")); } System.out.println(student); }
使用内省
public void neixing() throws Exception { BeanInfo info = Introspector.getBeanInfo(Student.class); //获取某个属性的描述器 PropertyDescriptor pDescriptor=new PropertyDescriptor("name", Student.class); //获得某个类的所有描述器 // PropertyDescriptor[] pds = info.getPropertyDescriptors(); // BeanUtils.getP Method method=pDescriptor.getReadMethod(); System.out.println(method.getName()); //BeanUtils更方便 // BeanUtils.getProperty(bean, name, value) // BeanUtils.setProperty(bean, name, value) }
获得描述器后 getReadMethod(),getSetMethod() 就是对 Method method=clazz.getMethod("set"+captureName(f.getName()),Class.forName(sClassString));极大简化
BeanUtils
public void fun3() throws Exception { SAXReader reader = new SAXReader(); Document document = reader.read(this.getClass().getResourceAsStream("/beans.xml")); String xpath="/beans/bean[@id=\"stu1\"]"; Element element=(Element) document.selectSingleNode(xpath); Class clazz=Class.forName(element.attributeValue("className")); Student student=(Student) clazz.newInstance(); List<Element> els=element.elements(); System.out.println(student); for (Element e : els) { Field f=clazz.getDeclaredField(e.attributeValue("name")); BeanUtils.setProperty(student, f.getName(), e.attributeValue("value")); } System.out.println(student); }
beanUtils.getProperty
beanUtils.setPropert
简化了getMethod() ,和invoke()连个方法
使反射获得属性描述器并执行赋值/取值更方便
内省Introspector 和BeanUtils 工具对反射属性的包装(简单的不是一点点哦)
标签:des 对象 val 实例 elements eva gets 变量 tty
原文地址:http://www.cnblogs.com/lt123/p/7277187.html