利用java反射機制生成entity的一個例子

public void makeEntity(Element element ,List outlist) {

List l = element.getChild("disp").getChildren("column");

XmlcloumnsEntity  xmlcloumnsEntity=  new XmlcloumnsEntity();

for (int j = 0; j < l.size(); j++) {

xmlcloumnsEntity =  new XmlcloumnsEntity();

Element column = (Element)l.get(j);

elementToXmlcloumnsEntity(xmlcloumnsEntity,column) ;

outlist.add(xmlcloumnsEntity);

}

}

 

public XmlcloumnsEntity elementToXmlcloumnsEntity( XmlcloumnsEntity xmlEntity ,Element element ) {

Class clazz  = xmlEntity.getClass();

Field[] fields=clazz.getDeclaredFields();

for(int i=0;i < fields.length ; i ++ ){

Field field=fields[i];

String fieldName=field.getName();   

String stringLetter=fieldName.substring(0, 1).toUpperCase();

String setName="set"+stringLetter+fieldName.substring(1);

Method setMethod;

try {

setMethod = clazz.getMethod(setName, new Class[]{field.getType()});

setMethod.invoke(xmlEntity,new Object[]{element.getAttributeValue(fieldName)==null?"":element.getAttributeValue(fieldName)});

} catch (SecurityException e) {

e.printStackTrace();

} catch (NoSuchMethodException e) {

e.printStackTrace();

} catch (IllegalArgumentException e) {

e.printStackTrace();

} catch (IllegalAccessException e) {

e.printStackTrace();

} catch (InvocationTargetException e) {

e.printStackTrace();

}   

}

return xmlEntity;

}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章