黑马程序员技术交流社区
标题:
【上海校区】Java通过反射机制动态设置对象属性值
[打印本页]
作者:
不二晨
时间:
2018-12-21 09:24
标题:
【上海校区】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:
在开发过程中有类似的需求通过反射动态设置属性值,希望有帮助。也很高心与大家分享,谢谢。
---------------------
【转载】仅作分享,侵删
作者:老李的地下室
原文:
https://blog.csdn.net/u011148770/article/details/46954061
作者:
不二晨
时间:
2018-12-26 10:18
欢迎光临 黑马程序员技术交流社区 (http://bbs.itheima.com/)
黑马程序员IT技术论坛 X3.2