欢迎来到代码驿站!

JAVA代码

当前位置:首页 > 软件编程 > JAVA代码

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

时间:2021-03-14 09:51:15|栏目: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内部类作用的深入分析

栏    目:JAVA代码

下一篇:Java修改eclipse中web项目的server部署路径问题

本文标题:Java通过反射机制动态设置对象属性值的方法

本文地址:http://www.codeinn.net/misctech/80674.html

推荐教程

广告投放 | 联系我们 | 版权申明

重要申明:本站所有的文章、图片、评论等,均由网友发表或上传并维护或收集自网络,属个人行为,与本站立场无关。

如果侵犯了您的权利,请与我们联系,我们将在24小时内进行处理、任何非本站因素导致的法律后果,本站均不负任何责任。

联系QQ:914707363 | 邮箱:codeinn#126.com(#换成@)

Copyright © 2020 代码驿站 版权所有