Chinaunix首页 | 论坛 | 博客
  • 博客访问: 2538658
  • 博文数量: 308
  • 博客积分: 5547
  • 博客等级: 大校
  • 技术积分: 3782
  • 用 户 组: 普通用户
  • 注册时间: 2009-11-24 09:47
个人简介

hello world.

文章分类

全部博文(308)

分类: Java

2016-06-16 09:54:01


点击(此处)折叠或打开

  1. package com.common.xml;

  2. import java.lang.reflect.Field;

  3. //将java对象,格式化为xml格式输出,方便监控java对象的相关参数
  4. //author:程晓鹏
  5. //date:2016.05.19
  6. public class Java2Xml {
  7.     
  8.     private String[] javaNormalType = {"byte", "shot", "int", "long", "float", "double", "char", "boolean", "String", "Object"}; //java基本数据类型
  9.     public enum DisplayType {Normal, Lower, Upper}; //xml节点显示类型
  10.     private String[] filterTypeCollection = null;
  11.     private String[] filterClassCollection = null;
  12.     private StringBuilder result = null;
  13.     private String strOffset = ""; //偏移量填充字符
  14.     private DisplayType _type;
  15.     
  16.     //默认构造函数
  17.     public Java2Xml(){
  18.         strOffset = "\t";
  19.         _type = DisplayType.Normal;
  20.         result = new StringBuilder();
  21.         
  22.     }
  23.     
  24.     //加载java对象
  25.     public void loadJavaObject(Object data){
  26.         result.setLength(0);
  27.         this.build(data, 0, "");
  28.     }
  29.     
  30.     //获取xml结果值
  31.     public String getXmlResult(){
  32.         return result.toString();
  33.     }
  34.     
  35.     //获取xml结果值
  36.     public String getXmlResult0(){
  37.         String result = this.getXmlResult();
  38.         return result.substring(0, result.length()-1);
  39.     }
  40.     
  41.     //构建数组集合对象
  42.     private void buildListType1(Object data, int offset, String className){
  43.      ++offset;
  44.       String strClassName = getClassName(className, ";");
  45.       getLogInfo(getXmlItem(strClassName), offset); //添加List节点            
  46.       buildListData(data, offset);
  47.      getLogInfo(getXmlItemEnd(strClassName), offset);    
  48.       --offset;
  49.     }
  50.     
  51.     //构建List对象集合类型
  52.     private void buildListType2(Object data, int offset, String className){
  53.         if(data != null){
  54.      ++offset;
  55.      String strClassName = getClassName(className, ">"); //获取真实的类名
  56.      getLogInfo(getXmlItem(strClassName), offset); //添加List节点
  57.      Field[] field = data.getClass().getDeclaredFields();
  58.      for(int i=0; i<field.length; i++){
  59.          String strClassName2 = getClassName(field[i].getGenericType().toString(),";");
  60.          if("object".equals(strClassName2.toLowerCase())){
  61.              try {
  62.                  field[i].setAccessible(true); //设置可访问数据
  63.                         buildListData(field[i].get(data), offset); //构建list集合数据
  64.                     } catch (IllegalArgumentException e) {
  65.                         // TODO Auto-generated catch block
  66.                         e.printStackTrace();
  67.                     } catch (IllegalAccessException e) {
  68.                         // TODO Auto-generated catch block
  69.                         e.printStackTrace();
  70.                     }
  71.          }
  72.      }
  73.             getLogInfo(getXmlItemEnd(strClassName), offset);
  74.         }
  75.     }
  76.     
  77.     //构建有java基本数据类型,构建的泛型集合对象 程晓鹏 2016.05.25 add
  78.     private void buildListType3(Object data, int offset, String className, String memeberName){
  79.         if(data != null){
  80.             String strClassName = getClassName(className, ">"); //获取真实的类名        
  81.      ++offset;
  82.      getLogInfo(getXmlItem(memeberName), offset); //添加List节点,采用成员名称,作为节点名称
  83.      Field[] field = data.getClass().getDeclaredFields();
  84.      for(int i=0; i<field.length; i++){
  85.          String strClassName2 = getClassName(field[i].getGenericType().toString(),";");
  86.          if("object".equals(strClassName2.toLowerCase())){
  87.              try {
  88.                  field[i].setAccessible(true); //设置可访问数据
  89.                         buildListData2(field[i].get(data), offset, strClassName); //构建list集合数据
  90.                     } catch (IllegalArgumentException e) {
  91.                         // TODO Auto-generated catch block
  92.                         e.printStackTrace();
  93.                     } catch (IllegalAccessException e) {
  94.                         // TODO Auto-generated catch block
  95.                         e.printStackTrace();
  96.                     }
  97.          }
  98.      }
  99.             getLogInfo(getXmlItemEnd(memeberName), offset);
  100.             
  101.         }
  102.     }
  103.     
  104.     //构建由java基础类型,创建的数组类型
  105.     private void buildListType4(Object data, int offset, String className, String memeberName){
  106.         if(data != null){
  107.      ++offset;
  108.      String strClassName = getClassName(className, ";"); //获取真实的类名
  109.      getLogInfo(getXmlItem(memeberName), offset); //添加List节点,采用成员变量名称
  110.      Object len = java.lang.reflect.Array.getLength(data);
  111.      int iLen = Integer.parseInt(len.toString());
  112.      for(int i=0; i<iLen; i++){
  113.          Object arrayObj = java.lang.reflect.Array.get(data, i);
  114.                 if(arrayObj != null){
  115.                     ++offset;
  116.                     getLogInfo(getXmlItem(strClassName, arrayObj.toString()),offset); //添加叶子节点
  117.                     --offset;
  118.                 }
  119.      }
  120.             getLogInfo(getXmlItemEnd(memeberName), offset);
  121.         }
  122.     }
  123.     
  124.   //构建集合数据
  125.     private void buildListData(Object data, int offset){
  126.         if(data != null){
  127.             Object len = java.lang.reflect.Array.getLength(data);
  128.      int iLen = Integer.parseInt(len.toString());
  129.             for (int j=0; j<iLen; j++){
  130.                 Object arrayObj = java.lang.reflect.Array.get(data, j);
  131.                 if(arrayObj != null){
  132.                  this.build(arrayObj, ++offset, "item"); //进行递归调用
  133.                  --offset;
  134.                 }
  135.             }
  136.         }
  137.     }
  138.     
  139.     //构建由java基础类型,创建的泛型集合成员 程晓鹏2016.05.25 add
  140.     private void buildListData2(Object data, int offset, String className){
  141.         if(data != null){
  142.             Object len = java.lang.reflect.Array.getLength(data);
  143.      int iLen = Integer.parseInt(len.toString());
  144.             for (int j=0; j<iLen; j++){
  145.                 Object arrayObj = java.lang.reflect.Array.get(data, j);
  146.                 if(arrayObj != null){
  147.                     ++offset;
  148.                     getLogInfo(getXmlItem(className, arrayObj.toString()),offset); //添加叶子节点
  149.                     --offset;
  150.                 }            
  151.             }
  152.         }
  153.     }
  154.     
  155.     //构建叶子节点
  156.     private void buildLeafNode(String memberName, Object data, int offset){
  157.         String memberValue = "null"; //默认值为null
  158.         if(data != null){                        
  159.             memberValue =data.toString();
  160.         }
  161.         ++offset;
  162.         getLogInfo(getXmlItem(memberName, memberValue),offset); //添加叶子节点
  163.         --offset;
  164.     }
  165.     
  166.     //构建单List泛型集合对象 程晓鹏 2017.03.03 add
  167.     private void buildListData2_2(Object data, int offset, String className){
  168.         if(data != null){
  169.             Object len = java.lang.reflect.Array.getLength(data);
  170.      int iLen = Integer.parseInt(len.toString());
  171.             for (int j=0; j<iLen; j++){
  172.                 Object arrayObj = java.lang.reflect.Array.get(data, j);
  173.                 if(arrayObj != null){
  174.                     ++offset;
  175.                     this.build(arrayObj, offset, "");
  176.                     --offset;
  177.                 }            
  178.             }
  179.         }
  180.     }
  181.     
  182.     //支撑单List泛型集合对象 程晓鹏 2017.03.03 add
  183.     private void buildSingleList(Object obj, int offset, String xmlNode){
  184.         try {
  185.             getLogInfo(getXmlItem(xmlNode),offset); //添加开始节点
  186.             Field[] field = obj.getClass().getDeclaredFields();
  187.             Field myfield = field[1];
  188.             myfield.setAccessible(true); //设置可访问数据
  189.             Object membObj = myfield.get(obj);            
  190.             buildListData2_2(membObj, offset, xmlNode); //采用新的构建方法 程晓鹏 2017.03.03 add
  191.             getLogInfo(getXmlItemEnd(xmlNode),offset); //添加结束节点
  192.             return;
  193.         } catch (IllegalArgumentException e) {
  194.             e.printStackTrace();
  195.         } catch (IllegalAccessException e) {
  196.             e.printStackTrace();
  197.         } //获取私有成员数据    
  198.     }
  199.     
  200.     //进行构建
  201.     private void build(Object data, int offset, String xmlNode){
  202.         Field[] field = data.getClass().getDeclaredFields();
  203.         String strRootClass = getClassName(data.getClass().getName());
  204.         String strXmlNode = "".equals(xmlNode)?strRootClass:xmlNode; //节点名称
  205.         int iDataType = validDataType(strXmlNode, "");
  206.         if(iDataType == 6){    
  207.             this.buildSingleList(data, offset, strXmlNode); //支撑单List泛型集合对象 程晓鹏 2017.03.03 add
  208.             return;
  209.         }else if (iDataType == 7){
  210.             String className = strXmlNode.substring(0, strXmlNode.length()-1); //去掉最后一个';'字符
  211.             this.buildListType1(data, --offset, className); //支撑单List泛型集合对象 程晓鹏 2017.03.03 add
  212.             return;
  213.         }else{
  214.             ;
  215.         }
  216.         
  217.         getLogInfo(getXmlItem(strXmlNode),offset); //添加开始节点        
  218.         for(int i=0; i<field.length; i++){
  219.             String strMemberName = field[i].getName(); //成员变量名称    
  220.             String strSubClassName = field[i].getGenericType().toString();
  221.             iDataType = validDataType(strSubClassName, strMemberName); //验证数据类型            
  222.             try {
  223.                 field[i].setAccessible(true); //设置可访问数据
  224.                 Object membObj = field[i].get(data); //获取私有成员数据                
  225.                 //field[i].getModifiers() Java语言修饰符返回整数编码。修饰符包括public, protected, private, final, static, abstract 和interface及Java虚拟机的常数
  226.                 //field[i].getModifiers()=10;为静态成员
  227.                 if(10==field[i].getModifiers() && 2!=iDataType){ //对类中的静态成员进行过滤掉
  228.                     continue;
  229.                 }else if(membObj==null && 2!=iDataType){ //当节点为null时,跳过
  230.                     continue;
  231.                 }else if (iDataType < 0){ //过滤的类型,直接跳过
  232.                     continue;
  233.                 }else if (1 == iDataType){ //构建对象集合类型
  234.                     buildListType1(membObj, offset, strSubClassName);
  235.                 }else if (3 == iDataType){ //构建List对象集合类型
  236.                     buildListType2(membObj, offset, strSubClassName);
  237.                 }else if (4 == iDataType){ //构建java基础类型,创建的List对象集合
  238.                     buildListType3(membObj, offset, strSubClassName, strMemberName);
  239.                 }else if (5 == iDataType){ //构建java基础类型,创建的数组类型
  240.                     buildListType4(membObj, offset, strSubClassName, strMemberName);;
  241.                 }else if (2 == iDataType){
  242.                     buildLeafNode(strMemberName, membObj, offset); //构建叶子节点
  243.                 }else{
  244.                     this.build(membObj, ++offset, ""); //进行递归调用
  245.                     --offset; //递归完成处理后,将偏移量--
  246.                 }
  247.             }catch (IllegalArgumentException e) {
  248.                 // TODO Auto-generated catch block
  249.                 e.printStackTrace();
  250.             } catch (IllegalAccessException e) {
  251.                 // TODO Auto-generated catch block
  252.                 e.printStackTrace();
  253.             }            
  254.         }
  255.         getLogInfo(getXmlItemEnd(strXmlNode),offset); //添加结束节点
  256.     }
  257.     
  258.     //验证数据类型
  259.     //clasName:类名称(包含包);memberName:成员变量名称
  260.     //0:默认值; 1:是集合成员; -1:是过滤成员;2:java关键字
  261.     private int validDataType(String className, String memberName){
  262.         int result = 0;
  263.         String strPackage = getGenericType(className); //包名称
  264.         String strCalssName = getClassName(strPackage); //真实的类名
  265.         if(validFilterMemberKey(memberName)){ //过滤的数据类型
  266.             result = -1;
  267.         }else if(validFilterClassKey(strPackage)){ //过滤的类名称
  268.             result = -2;
  269.         }else if(className.indexOf("[L")>0){ //判断是否是数组集合成员
  270.             strCalssName = getClassName(strPackage, ";"); //重新获取,真实的类名
  271.             if(validJavaDataTypeKey(strCalssName)){
  272.                 result = 5; //java基础类型,创建的数组类型
  273.             }else{
  274.                 result = 1; //类结构的数组
  275.             }
  276.         }else if(className.indexOf("List<")>0){ //判断是否为List集合成员
  277.             strCalssName = getClassName(strPackage, ">"); //重新获取,真实的类名
  278.             if(validJavaDataTypeKey(strCalssName)){
  279.                 result = 4; //类型为java关键字的泛型集合
  280.             }else{
  281.                 result = 3; //为泛型集合类型
  282.             }
  283.         }else if(validJavaDataTypeKey(strCalssName)){ //java关键字
  284.             result = 2;
  285.         }else if(strCalssName.equals("ArrayList")){
  286.             result = 6; //为独立的List对象 程晓鹏 2017.03.03 add
  287.         }else if (className.indexOf(";")>0){
  288.             result = 7; //为独立的数组对象 程晓鹏 2017.03.03 add
  289.         }
  290.         else{
  291.             ;
  292.         }
  293.         return result;
  294.     }
  295.     
  296.     //获取xml节点项
  297.     private String getXmlItem(String xmlNode, String text){
  298.         StringBuilder sb = new StringBuilder();
  299.         sb.append(getXmlItem(xmlNode));
  300.         sb.append(text);
  301.         sb.append(getXmlItemEnd(xmlNode));
  302.         
  303.         return sb.toString();
  304.     }
  305.     
  306.     //获取xml开始节点
  307.     private String getXmlItem(String xmlNode){
  308.         StringBuilder sb = new StringBuilder();
  309.         sb.append("<");
  310.         sb.append(getXmlNode(xmlNode));
  311.         sb.append(">");
  312.         
  313.         return sb.toString();
  314.     }
  315.     
  316.     //获取xml结束节点
  317.     private String getXmlItemEnd(String xmlNode){
  318.         StringBuilder sb = new StringBuilder();
  319.         sb.append(");
  320.         sb.append(getXmlNode(xmlNode));
  321.         sb.append(">");
  322.         
  323.         return sb.toString();
  324.     }
  325.     
  326.     private String getXmlNode(String xmlNode){
  327.         String result = "";
  328.         switch(this._type){
  329.         case Normal:
  330.             result = xmlNode;
  331.             break;
  332.         case Upper:
  333.             result =xmlNode.toUpperCase();
  334.             break;
  335.         case Lower:
  336.             result = xmlNode.toLowerCase();
  337.              break;
  338.         default:
  339.             result = xmlNode;
  340.             break;
  341.         }
  342.         
  343.         return result;
  344.     }
  345.     
  346.     //获取日志信息
  347.     private void getLogInfo(String data, int offset){
  348.         StringBuilder strXmlItem = new StringBuilder();
  349.         strXmlItem.append(printOffsetStr(offset));
  350.         strXmlItem.append(data);
  351.         strXmlItem.append("\n");
  352.         
  353.         //System.out.print(strXmlItem.toString()); //打印
  354.         result.append(strXmlItem);
  355.     }
  356.     
  357.     //打印偏移数据量
  358.     private String printOffsetStr(int size){
  359.         StringBuilder result = new StringBuilder();
  360.         for(int i=0; i<size; i++){
  361.             result.append(this.strOffset);
  362.         }
  363.         
  364.         return result.toString();
  365.     }
  366.     
  367.     //设置过滤成员集合数据,打印参数不打印该数据
  368.     public void setFilterMemberCollection(String[] data){
  369.         this.filterTypeCollection = data;
  370.     }
  371.     
  372.     //设置过滤的类集合数据,打印参数不打印该数据
  373.     public void setFilterClassCollcetin(String[] data){
  374.         this.filterClassCollection = data;
  375.     }
  376.     
  377.     //设置偏移字符串
  378.     public void setOffsetString(String offsetStr){
  379.         this.strOffset = offsetStr;
  380.     }
  381.     
  382.     public void setXmlNodeType(DisplayType type){
  383.         this._type = type;
  384.     }
  385.     
  386.     //验证java数据类型是否为java基本数据类型
  387.     private boolean validJavaDataTypeKey(String key){
  388.         boolean result = false;
  389.         for(int i=0; i<javaNormalType.length; i++){
  390.             if (key.toLowerCase().equals(javaNormalType[i].toLowerCase())){
  391.                 result = true;
  392.                 break;
  393.             }
  394.         }
  395.         return result;
  396.     }
  397.     
  398.     //验证过过滤成员
  399.     private boolean validFilterMemberKey(String key){
  400.         boolean result = false;
  401.         if(filterTypeCollection != null && filterTypeCollection.length > 0){
  402.             for(int i=0; i<filterTypeCollection.length; i++){
  403.                 if (key.toLowerCase().equals(filterTypeCollection[i].toLowerCase())){
  404.                     result = true;
  405.                     break;
  406.                 }
  407.             }
  408.         }
  409.         return result;
  410.     }
  411.     
  412.     //验证过滤的信息
  413.     private boolean validFilterClassKey(String key){
  414.         boolean result = false;
  415.         if(this.filterClassCollection != null && filterClassCollection.length > 0){
  416.             for(int i=0; i<filterClassCollection.length; i++){
  417.                 if (key.toLowerCase().equals(filterClassCollection[i].toLowerCase())){
  418.                     result = true;
  419.                     break;
  420.                 }
  421.             }
  422.         }
  423.         return result;
  424.     }
  425.     
  426.     //获取类型,去除前面的"class "字符串
  427.     private String getGenericType(String data){
  428.         String result = "";
  429.         if(data.length() > 6 && data.indexOf("class ")!=-1){
  430.             result = data.substring(6, data.length());
  431.         }else{
  432.             result = data;
  433.         }
  434.         return result;
  435.     }
  436.     
  437.     //获取类名称
  438.     private String getClassName(String data){
  439.         String result = "";
  440.         int idx = data.lastIndexOf("."); //类名全路径最后一个.的位置,为获取类名称做准备
  441.         if (idx != -1){
  442.             ++idx;
  443.             result = data.substring(idx, data.length());
  444.         }else{
  445.             result = data;
  446.         }
  447.         return result;
  448.     }
  449.     
  450.     //获取类名2
  451.     private String getClassName(String data, String endChar){
  452.         String result = "";
  453.         int idx = data.lastIndexOf("."); //类名全路径最后一个.的位置,为获取类名称做准备
  454.         int idx2 = data.lastIndexOf(endChar);
  455.         if (idx != -1 && idx2 != -1){
  456.             ++idx;
  457.             result = data.substring(idx, idx2);
  458.         }else if(idx != -1 && idx2<0){
  459.             ++idx;
  460.             result = data.substring(idx, data.length());
  461.         }else{
  462.             result = data;
  463.         }
  464.         return result;
  465.     }
  466. }


Java2Xml.rar

阅读(2474) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~