源码网商城,靠谱的源码在线交易网站 我的订单 购物车 帮助

源码网商城

Java通过反射机制动态设置对象属性值的方法

  • 时间:2022-07-03 21:13 编辑: 来源: 阅读:
  • 扫一扫,手机访问
摘要:Java通过反射机制动态设置对象属性值的方法
/**
  * MethodName: getReflection<br>
  * Description:解析respXML 在通过反射设置对象属性值
  * User: liqijing
  * Date:2015-7-19下午12:42:55
  * @param clzzName 
  * @param respXML 
  * @return
  * @throws ClassNotFoundException
  * @throws DocumentException
  * @throws IllegalArgumentException
  * @throws IllegalAccessException
  * @throws InstantiationException
  * @throws SecurityException
  * @throws NoSuchFieldException
  */
 public static <T> Object getReflection(String clzzName , String respXML) throws ClassNotFoundException, DocumentException, IllegalArgumentException, IllegalAccessException, InstantiationException, SecurityException, NoSuchFieldException{
  Object o = Class.forName(clzzName).newInstance();
  Class clz = Class.forName(clzzName).newInstance().getClass();
  Document doc = null ;
  doc = DocumentHelper.parseText(respXML);
  Element el = doc.getRootElement();
  for (Field f : clz.getDeclaredFields()){
   Iterator it=el.elementIterator();
   while(it.hasNext()){
    Element elt = (Element) it.next();
    if(f.getName().equals(elt.getName())){
     f = clz.getDeclaredField(elt.getName());
     f.setAccessible(true);
     f.set(o, elt.getText());
    }
   }
  }
  return o;
 }
Dear All: 在开发过程中有类似的需求通过反射动态设置属性值,希望有帮助。也很高兴与大家分享,谢谢。 以上这篇Java通过反射机制动态设置对象属性值的方法就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持编程素材网。
  • 全部评论(0)
联系客服
客服电话:
400-000-3129
微信版

扫一扫进微信版
返回顶部