将Java对象保存为XML文档

package com.kiloway.trace.utils; import java.lang.reflect.Field; /** * @author Zhang Qi * @Create Time 2010/01/09 * */ public class ObjectToXML { public String toString(Object object) throws Exception { StringBuilder sb = new StringBuilder(); //得到类的名称 String classname = object.getClass().getSimpleName(); //得到类有哪些字段 Field[] fields = object.getClass().getDeclaredFields(); //以字段名称作为节点 sb.append("<" + classname + ">/n"); for (int i = 0; i < fields.length; i++) { sb.append("/t<" + fields[i].getName() + ">"); //设置字段属性的访问权限 fields[i].setAccessible(true); //获取字段属性 sb.append(fields[i].get(object)); sb.append("</" + fields[i].getName() + ">/n"); } sb.append("</" + classname + ">/n"); return sb.toString(); } }

你可能感兴趣的:(java,xml,exception,String,object,Class)