Java reflection principle Making object Printing tool _java

Source: Internet
Author: User

Mainly using the Java reflection principle, format output Java object attribute values, especially list and 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; /** * This class is a convenient console output object, the main application of Java reflection mechanism.
 Because of the use and aesthetics, no infinite recursion is used.
 * Instead, add a Boolean recursion to the Tostr method, whether recursive.
 * Of course, we can also change the boolean recursion to int recursion to control the number of recursive times.
  * In fact, with my experience, complex data ToString is a good way to convert JSON into JSON output.
    This is the way I use Boolean recursion whether recursive public static int add (int i,boolean recursion) {sum+=i;
    if (recursion) Add (I, false);
  return sum;
    //You can do this, int recursion represents a recursive count of 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 = "=";//Split Line Stati C final String my_sign = "klg_print";//implicitly label private static string date_format = "yyyy-mm-dd HH:mm:ss ";  /** * The collection type Tosring method * @param Object * @param recursion * Whether recursive * @return/private static String
    Collectiontostr (Object, Boolean recursion) {if (object = = null) return "NULL";
    object[] a = null;
    Converts a collection type to an array type if (Isarraytype (object)) A = (object[]) object;
    else A = ((Collection) object). ToArray ();
    if (Issimplearr (a) | |!recursion) return arrays.tostring (a);
  else return Complexarrtostr (a); /** * Arrays has the ToString method, but the object content is too much, on one line there is no index information displayed/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 Type tostring Method * * @param map * @param recursion * Whether recursive * @return/private static STR
    ing Maptostr (map<string, object> map, Boolean recursion) {if (map = = NULL) return "NULL";
    if (Issimplemap (map) | |!recursion) return SIMPLEMAPTOSTR (map);
  else return Complexmaptostr (map, true); The value of the/** * map is a simple type, and the copy map.tostring, I add a newline 10 lines * * @param map * @return/private static Strin
    G 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% = = 0 && T!= 0) sb.append ("\ r \ n");    } private static String complexmaptostr (map map, Boolean recursion) {iterator<entry<string, object&
    gt;> 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 * Whether to recursive * @return/private static STR
    ing Beantostr (object, Boolean recursion) {if (object = = null) return "NULL";
    Class clazz = Object.getclass (); StriNgbuilder sb = new StringBuilder ();
    Returns the abbreviation Sb.append (Clazz.getsimplename ()) of the underlying class given in the source code. 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);/set some properties are accessible String name = Field.getname ();//Gets the name of the field if (Name.equals ("Serialve
      Rsionuid ")) continue; try {Object value = Field.get (object);//Get the value of this property if (Issimpletype (value) | |!recursion) Sb.appe
        ND (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 (","); The 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 Issimp  Letype (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 STA
    Tic Boolean iscollectiontype (Object obj) {if (obj = null) return false; Return (Obj.getclass (). IsArray () | |
  (obj instanceof Collection));
    The private static Boolean isarraytype (Object obj) {if (obj = null) return false;
  Return (Obj.getclass (). IsArray ());
    The 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 (OB
    j)) 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; /*** * The simple type in front * @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] is a simple type regardless of//fields[i] is a complex type//Int j = i+1, starting from fields[i] compare for (int j = i + 1; J < Fields.lenGth
        J + +) {Field fieldtmp = null;
          if (Issimpletype (Fields[j].gettype ())) {//interacting with the first simple type later fieldtmp = Fields[i];
          Fields[i] = Fields[j];
          FIELDS[J] = fieldtmp; Break
  The back of the loop, is meaningless de}} return fields;
   /** * This method is recursive and is called in multiple places, taking into account circular references and display formats, Boolean recursion to make sure that recursion can be terminated. * @param Object * @param recursion * requires a deeper display * @return/private static String Objtostr (objec
    T 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 (split_line) + "" +ob
    J.getclass (). Getsimplename () + ">>" + sign + "" + indent (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));

 }
}

However, the above code is too cumbersome to consider multiple types of nesting problems.
Array type strong transfer newspaper classcastexception.
It is much clearer to use log4j to write a tool in the usual way than to make a log.

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));
}

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.