根据类名反射得到其属性及属性值,属性为XML标签,属性值为XML标签值。
import java.lang.reflect.Field; import java.lang.reflect.Method; import java.util.List; /** * 根据反射生成XML * @author 喻克 * */ public class ObjectToXml { /** * 根据类名反射得到其属性及属性值 * 属性为XML标签,属性值为XML标签值 * @param object * @return String * @throws Exception */ public static String ObjecttoXML(Object object) throws Exception { Class<? extends Object> classType = object.getClass(); //属性集合 Field[] fields = classType.getDeclaredFields(); String xml = ""; for (Field field : fields) { String fieldName = field.getName();//属性名称 String stringLetter = fieldName.substring(0,1).toUpperCase(); // 获得object对象相应的get方法 String getName = "get" + stringLetter + fieldName.substring(1); // 获取相应的方法 Method getMethod = classType.getMethod(getName,new Class[] {}); // 调用源对象的get方法的值 Object getValue = getMethod.invoke(object,new Object[] {}); if (null == getValue) { getValue = ""; } xml += "<" + fieldName + ">" + getValue + "</" + fieldName + ">"; } xml ="<object>" + xml + "</object>"; return xml; } /** * 根据类名反射得到其属性及属性值 * 属性为XML标签,属性值为XML标签值 * @param objectList * @return String * @throws Exception */ public static String ObjecttoXML(List<Object> objectList) throws Exception { String xml = ""; xml += "<objects>"; for (int i = 0; i < objectList.size(); i++) { Object object = objectList.get(i); Class<? extends Object> classType = object.getClass(); Field[] fields = classType.getDeclaredFields(); xml += "<object>"; for (Field field : fields) { String fieldName = field.getName(); String stringLetter = fieldName.substring(0,1).toUpperCase(); String getName = "get" + stringLetter + fieldName.substring(1); Method getMethod = classType.getMethod(getName,new Class[] {}); Object getValue = getMethod.invoke(object,new Object[] {}); if (null == getValue) { getValue = ""; } xml += "<" + fieldName + ">" + getValue + "</" + fieldName + ">"; } xml += "</object>"; } xml += "</objects>"; return xml; } }原文链接:https://www.f2er.com/xml/299502.html