根据类名反射得到其属性及属性值,属性为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; } }
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。