程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
 程式師世界 >> 編程語言 >> JAVA編程 >> 關於JAVA >> java反射道理制造對象打印對象

java反射道理制造對象打印對象

編輯:關於JAVA

java反射道理制造對象打印對象。本站提示廣大學習愛好者:(java反射道理制造對象打印對象)文章只能為提供參考,不一定能成為您想要的結果。以下是java反射道理制造對象打印對象正文


重要應用java反射道理,格局化輸入java對象屬性值,特殊是list 和map。

 MyTestUtil.java

package utils;
 
import java.lang.reflect.Field;
import java.text.SimpleDateFormat;
import java.util.Arrays;
import java.util.Collection;
import java.util.Date;
import java.util.Iterator;
import java.util.Map;
import java.util.Map.Entry;
 
 
/**
 * 這個類是便利掌握台輸入object,重要運用java反射機制。 由於斟酌到應用性和雅觀性,沒有應用無窮遞歸。
 * 而是在toStr辦法中參加一個boolean recursion ,能否遞歸。
 * 固然我們也能夠將boolean recursion換成int recursion,掌握遞歸次數。
 * 其實就我應用經歷來看,龐雜數據toString,用json對象轉化成json輸入是一個不錯的方法。
  //這是我用的方法,boolean recursion能否遞歸
  public static int add(int i,boolean recursion){
    sum+=i;
    if(recursion)
      add(i, false);
    return sum;
  }
  //也能夠如許,int recursion表現遞歸次數
  public static int add(int i,int recursion){
    sum+=i;
    if(recursion>0){
      recursion--;
      add(i, recursion);
    }
    return sum;
  }
 * 
 * 
 * @author klguang
 * 
 */
   
public class MyTestUtil {  
  static final String SPLIT_LINE = "=";// 朋分線
  static final String MY_SIGN = "KLG_print";//默認標記
  private static String DATE_FORMAT = "yyyy-MM-dd HH:mm:ss";
 
  /**
   * 將聚集類型toSring辦法
   * @param object
   * @param recursion
   *      能否遞歸
   * @return
   */
  private static String collectionToStr(Object object, boolean recursion) {
    if (object == null)
      return "null";
    Object[] a = null;
    // 將聚集類型轉換成數組類型
    if (isArrayType(object))
      a = (Object[]) object;
    else
      a = ((Collection) object).toArray();
    if (isSimpleArr(a) || !recursion)
      return Arrays.toString(a);
    else
      return complexArrToStr(a);
  }
 
  /**
   * Arrays有toString辦法,然則對象內容太多,在一行顯示 還有就是沒有顯示index信息
   */
  private static String complexArrToStr(Object[] a) {
    if (a == null)
      return "null";
 
    int iMax = a.length - 1;
    if (iMax == -1)
      return "[]";
 
    StringBuilder b = new StringBuilder();
    for (int i = 0;; i++) {
      String value = objToStr(a[i], false);
      b.append("[" + i + "]" + " -> " + value);
      if (i == iMax)
        return b.toString();
      b.append(", \r\n");
    }
  }
 
  /**
   * map類型toString辦法
   * 
   * @param map
   * @param recursion
   *      能否遞歸
   * @return
   */
  private static String mapToStr(Map<String, Object> map, boolean recursion) {
    if (map == null)
      return "null";
    if (isSimpleMap(map) || !recursion)
      return simpleMapToStr(map);
    else
      return complexMapToStr(map, true);
  }
 
  /**
   * map的value是簡略類型的,復制Map.toString,我給它加了換行10個換行
   * 
   * @param map
   * @return
   */
  private static String simpleMapToStr(Map map) {
    Iterator<Entry<String, Object>> i = map.entrySet().iterator();
    if (!i.hasNext())
      return "{}";
 
    StringBuilder sb = new StringBuilder();
    sb.append('{');
    for (int t = 1;; t++) {
      Entry<String, Object> e = i.next();
      sb.append(e.getKey()).append(" = ").append(e.getValue());
      if (!i.hasNext())
        return sb.append('}').toString();
      sb.append(',').append(' ');
      if (t % 10 == 0 && t != 0)
        sb.append("\r\n ");
    }
  }
 
  private static String complexMapToStr(Map map, boolean recursion) {
    Iterator<Entry<String, Object>> i = map.entrySet().iterator();
    if (!i.hasNext())
      return "{}";
    StringBuilder sb = new StringBuilder();
    sb.append("{\r\n");
    for (int t = 1;; t++) {
      Entry<String, Object> e = i.next();
      String key = String.valueOf(e.getKey());
      Object value = e.getValue();
      sb.append(indent(2," ")).append(key).append(" = ");
      if (isSimpleType(value) || !recursion)
        sb.append(String.valueOf(value));
      else
        sb.append(objToStr(value, false));
      if (!i.hasNext())
        return sb.append("\r\n}").toString();
      sb.append(',').append("\r\n");
    }
  }
 
  /**
   * 
   * 
   * @param object
   * @param recursion
   *      能否要遞歸
   * @return
   */
  private static String beanToStr(Object object, boolean recursion) {
    if (object == null)
      return "null";
    Class clazz = object.getClass();
    StringBuilder sb = new StringBuilder();
    //前往源代碼中給出的底層類的簡稱
    sb.append(clazz.getSimpleName()).append("[");
    Field[] fields = sortFieldByType(clazz.getDeclaredFields());
    int iMax = fields.length - 1;
    if (iMax == -1)
      return sb.append("]").toString();
    for (int i = 0;; i++) {
      Field field = fields[i];
      field.setAccessible(true);// 設置些屬性是可以拜訪的
      String name = field.getName();// 獲得field的稱號
      if (name.equals("serialVersionUID"))
        continue;
      try {
        Object value = field.get(object);// 獲得此屬性的值
        if (isSimpleType(value) || !recursion)
          sb.append(name + " = " + String.valueOf(value));
        else
          sb.append("\r\n" + indent(clazz.getSimpleName().length() + 2," ")
              + objToStr(value, false) + "\r\n");
      } catch (Exception e) {
        e.printStackTrace();
      }
      if (i == iMax)
        return sb.append("]").toString();
      sb.append(",");
    }
  }
 
 
 
  private static String indent(int length,String sign) {
    StringBuilder sb = new StringBuilder();
    for (int i = 0; i < length; i++) {
      sb.append(sign);
    }
    return sb.toString();
  }
 
  private static boolean isSimpleType(Object obj) {
    if (obj == null)
      return true;
    else {
      Class objectClass = obj.getClass();
      return isSimpleType(objectClass);
    }
  }
 
  /**
   * 
   * @param objectClass
   *      用obj.getClass()獲得
   * @return
   */
  private static boolean isSimpleType(Class objectClass) {
    if (objectClass == boolean.class || objectClass == Boolean.class
        || objectClass == short.class || objectClass == Short.class
        || objectClass == byte.class || objectClass == Byte.class
        || objectClass == int.class || objectClass == Integer.class
        || objectClass == long.class || objectClass == Long.class
        || objectClass == float.class || objectClass == Float.class
        || objectClass == char.class || objectClass == Character.class
        || objectClass == double.class || objectClass == Double.class
        || objectClass == String.class) {
      return true;
    } else {
      return false;
    }
  }
 
  /**
   * Method isCollectionType
   * 
   * @param obj
   *      Object
   * @return boolean
   */
  private static boolean isCollectionType(Object obj) {
    if (obj == null)
      return false;
    return (obj.getClass().isArray() || (obj instanceof Collection));
  }
 
  private static boolean isArrayType(Object obj) {
    if (obj == null)
      return false;
    return (obj.getClass().isArray());
  }
 
  private static boolean isMapType(Object obj) {
    if (obj == null)
      return false;
    return (obj instanceof Map);
  }
   
  private static boolean isDateType(Object obj){
    if(obj==null)
      return false;
    return (obj instanceof Date);
  }
   
  private static boolean isBeanType(Object obj) {
    if (isSimpleType(obj) || isCollectionType(obj) || isMapType(obj))
      return false;
    else
      return true;
  }
 
  private static boolean isSimpleArr(Object[] a) {
    if (a == null || a.length < 1)
      return true;
    boolean flag = true;
    for (Object o : a) {
      if (!isSimpleType(o)) {
        flag = false;
        break;
      }
    }
    return flag;
  }
 
  private static boolean isSimpleMap(Map map) {
    if (map == null)
      return true;
    Iterator<Entry<String, Object>> i = map.entrySet().iterator();
    boolean flag = true;
    while (i.hasNext()) {
      Entry<String, Object> e = i.next();
      if (!isSimpleType(e.getValue())) {
        flag = false;
        break;
      }
    }
    return flag;
  }
 
  /***
   * 將簡略類型排在後面
   * @param fields
   * @return
   */
 
  public static Field[] sortFieldByType(Field[] fields) {
    for (int i = 0; i < fields.length; i++) {
      if (isSimpleType(fields[i].getType()))
        continue;// fields[i]是簡略類型不論
      // fields[i]是龐雜類型
      // int j = i+1,從fields[i]以後開端比擬
      for (int j = i + 1; j < fields.length; j++) {
        Field fieldTmp = null;
        if (isSimpleType(fields[j].getType())) {// 與前面的第一個簡略類型交互
          fieldTmp = fields[i];
          fields[i] = fields[j];
          fields[j] = fieldTmp;
          break; // 前面的輪回,是沒成心義de
        }
      }
    }
    return fields;
  }
 
  /**
   * 這個辦法是遞歸辦法,而且並多個處所挪用,斟酌到輪回援用和顯示格局, boolean recursion獲得確保遞歸可以被終止。
   * 
   * @param object
   * @param recursion
   *      能否須要更深一層顯示
   * @return
   */
  private static String objToStr(Object object, boolean recursion) {
    if (object == null)
      return "null";
    object.toString();
    if(isDateType(object))
      return new SimpleDateFormat(DATE_FORMAT).format((Date)object);
    else if (isBeanType(object))
      return beanToStr(object, recursion);
    else if (isCollectionType(object))
      return collectionToStr(object, recursion);
    else if (isMapType(object))
      return mapToStr((Map) object, recursion);
    else
      return String.valueOf(object);
  }
 
  public static String objToStr(Object obj) {
    return objToStr(obj, true);
  }
 
  private static void print(Object obj,String sign,String content) {
    String begin=indent(15, SPLIT_LINE) + " " +obj.getClass().getSimpleName()
      + " >> " + sign + " " + indent(10, SPLIT_LINE);
    int length=(begin.length()-sign.length()-5)/2;
     
    String end=indent(length, SPLIT_LINE)+ " " + sign + " " + indent(length, SPLIT_LINE);
    System.out.println(begin+"\r\n"+content+"\r\n"+end);
     
  }
  public static void print(Object obj){
    print(obj,MY_SIGN,objToStr(obj));
  }
  public static void printWithSign(String sign, Object obj) {
    print(obj, sign,objToStr(obj));
  }
}

不外呢下面代碼太繁瑣了,沒有斟酌多品種型嵌套的成績。
數組類型強轉會報ClassCastException 。
平凡打日記就用log4j寫個對象辦法 比下面這個清楚清楚明了多了。

public static void debug(String message,Object o){
int count=0;
if(o==null){
LOGGER.debug(chain(message,": null"));
return;
}
if(o.getClass().isArray()){
for(int i=0,len=Array.getLength(o);i<len;i++){
debug(chain(message,"-[",i,"]"),Array.get(o, i));
}
}else if(o instanceof Map){
Entry<?,?> e;
for(Iterator<?> it=((Map<?,?>)o).entrySet().iterator();it.hasNext();){
e=(Entry<?,?>) it.next();
debug(chain(message,"-[K:",e.getKey(),"]"),e.getValue());
}
}else if(o instanceof Iterable){
for(Iterator<?> it=((Iterable<?>) o).iterator();it.hasNext();){
count++; 
debug(chain(message,"-[",count,"]"),it.next());
}
}else{
LOGGER.debug(chain(message,":",o));
}
}

  1. 上一頁:
  2. 下一頁:
Copyright © 程式師世界 All Rights Reserved