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

网友投稿 200 2023-07-10


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

/**

* MethodName: getReflection

* Description:解析respXML 在通过反射设置对象属性值

* User: liqijing

* Datehttp://: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 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()http://){

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(truhttp://e);

f.set(o, elt.getText());

}

}

}

return o;

}

Dear All:

在开发过程中有类似的需求通过反射动态设置属性值,希望有帮助。也很高兴与大家分享,谢谢。


版权声明:本文内容由网络用户投稿,版权归原作者所有,本站不拥有其著作权,亦不承担相应法律责任。如果您发现本站中有涉嫌抄袭或描述失实的内容,请联系我们jiasou666@gmail.com 处理,核实后本网站将在24小时内删除侵权内容。

上一篇:关于input全选反选恶心的异常情况
下一篇:Java中枚举的使用详解
相关文章

 发表评论

暂时没有评论,来抢沙发吧~