Java reflect: A good debugging tool for printing object content

Source: Internet
Author: User
Tags int size stringbuffer

Back up a useful tool class. Typeutil
Its typetostring (String scope, Object obj) method uses the Java reflect mechanism to print out the contents of any object.
This is useful for debugging programs.
How to use:
If you have an object (such as Testclassobject) and want to print its contents, you can use the following methods:
System.out.println (typeutil.typetostring ("Yourclassobjectname", Testclassobject));
This method is useful for debugging EJB programs that are dependent on the container, and is hereby backed up.
The following are Typeutil source programs:
/**
* The Typeutil class static methods for inspecting complex Java types.
* The typetostring () is used to dump the contents of a passed object
* of any type (or collection) to a String. This can is very useful for debugging code
* Manipulates complex structures.
*
*
* @version $Revision: 1.2.6.4 $
*/


Import java.util.*;
Import java.lang.reflect.*;


public class Typeutil {


/**
* Returns A string holding the contents
* of the passed object,
* @param scope String
* @param parentobject Object
* @param visitedobjs List
* @return String
*/

private static string complextypetostring (string scope, Object parentobject,list visitedobjs) {

StringBuffer buffer = new StringBuffer ("");

try {
//
Ok, now we need to reflect into the object and add it child nodes ...
//


Class cl = Parentobject.getclass ();
while (CL!= null) {

Processfields (Cl.getdeclaredfields (),
Scope
ParentObject,
Buffer
VISITEDOBJS);

CL = Cl.getsuperclass ();
}
catch (Illegalaccessexception iae) {
Buffer.append (Iae.tostring ());
}

Return (buffer.tostring ());
}

/**
* Method Processfields
* @param fields field[]
* @param scope String
* @param parentobject Object
* @param buffer StringBuffer
* @param visitedobjs List
* @throws illegalaccessexception
*/
private static void Processfields (field[] fields,
String Scope,
Object ParentObject,
StringBuffer Buffer,
List Visitedobjs) throws Illegalaccessexception {

for (int i = 0; i < fields.length; i++) {

//
Disregard certain fields for IDL structures
//
if (Fields[i].getname (). Equals ("__discriminator")
|| Fields[i].getname (). Equals ("__uninitialized")) {
Continue
}

//
This is allows us to non-public fields. We might need to deal with some
SecurityManager issues here once it is outside of Vaj ...
//
Fields[i].setaccessible (TRUE);

if (Modifier.isstatic (Fields[i].getmodifiers ())) {
//
Ignore all static members. The classes this dehydrator is
Meant to handle are simple data objects, so static members have no
Bearing .....
//
} else {
Buffer.append (
Typetostring (Scope + "." + Fields[i].getname (), Fields[i].get (ParentObject), VISITEDOBJS));
}
}

}

/**
* Method Iscollectiontype
* @param obj Object
* @return Boolean
*/
public static Boolean iscollectiontype (Object obj) {

Return (Obj.getclass (). IsArray () | |
(obj instanceof Collection) | |
(obj instanceof Hashtable) | |
(obj instanceof HashMap) | |
(obj instanceof hashset) | |
(obj instanceof List) | |
(obj instanceof abstractmap));
}

/**
* Method Iscomplextype
* @param obj Object
* @return Boolean
*/
public static Boolean iscomplextype (Object obj) {

if (obj instanceof Boolean | |
Obj instanceof Short | |
obj instanceof Byte | |
obj instanceof Integer | |
obj instanceof Long | |
obj instanceof Float | |
obj instanceof Character | |
obj instanceof Double | |
obj instanceof String) {

return false;
}
else {

Class objectclass = Obj.getclass ();

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 false;

}

else {
return true;
}
}
}
/**
* Returns A string holding the contents
* of the passed object,
* @param scope String
* @param obj Object
* @param visitedobjs List
* @return String
*/

private static string collectiontypetostring (string scope, Object obj, List visitedobjs) {

StringBuffer buffer = new StringBuffer ("");

if (Obj.getclass (). IsArray ()) {
if (array.getlength (obj) > 0) {

for (int j = 0; J < array.getlength (obj); j +) {

Object x = Array.get (obj, j);

Buffer.append (typetostring (Scope + "[" + j + "]", X, Visitedobjs));
}

       } else {
             Buffer.append (Scope + "[]: empty/n");
       }
   } else {
        boolean iscollection = (obj instanceof Collection);
        Boolean ishashtable = (obj instanceof Hashtable);
        Boolean ishashmap = (obj instanceof HashMap);
        Boolean ishashset = (obj instanceof hashset);
        Boolean isabstractmap = (obj instanceof abstractmap);
        Boolean isMap = Isabstractmap | | ishashmap | | ishashtable;

if (ISMAP) {
Set keyset = ((MAP) obj). Keyset ();
Iterator iterator = Keyset.iterator ();
int size = Keyset.size ();

if (Size > 0) {

for (int j = 0; Iterator.hasnext (); j + +) {

Object key = Iterator.next ();
Object x = ((Map) obj). get (key);

                     Buffer.append (typetostring (Scope + "[/" "+ Key +"/"]", X, Visitedobjs));
               }
           } else {
                 Buffer.append (Scope + "[]: empty/n");
           }
       } else
             if (/*ishashtable | | */
                 IsCollection | | Ishashset/* | | Ishashmap */
               ) {

Iterator iterator = null;
int size = 0;

if (obj!= null) {

if (iscollection) {
iterator = ((Collection) obj). iterator ();
Size = ((Collection) obj). Size ();
} else
if (ishashtable) {
iterator = ((Hashtable) obj). values (). iterator ();
Size = ((Hashtable) obj). Size ();
} else
if (Ishashset) {
iterator = ((hashset) obj). iterator ();
Size = ((hashset) obj). Size ();
} else
if (Ishashmap) {
iterator = ((HashMap) obj). values (). iterator ();
Size = ((HASHMAP) obj). Size ();
}

if (Size > 0) {

for (int j = 0; Iterator.hasnext (); j + +) {

Object x = Iterator.next ();
Buffer.append (typetostring (Scope + "[" + j + "]", X, Visitedobjs));
}
} else {
Buffer.append (Scope + "[]: empty/n");
}
} else {
//
Theobject is null
Buffer.append (Scope + "[]: null/n");
}
}
}

Return (buffer.tostring ());

}
/**
* Method typetostring
* @param scope String
* @param obj Object
* @param visitedobjs List
* @return String
*/
private static string typetostring (string scope, Object obj, List visitedobjs) {

if (obj = = null) {
Return (Scope + ": null/n");
}
else if (Iscollectiontype (obj)) {
return collectiontypetostring (scope, obj, VISITEDOBJS);
}
else if (Iscomplextype (obj)) {
if (! visitedobjs.contains (obj)) {
Visitedobjs.add (obj);
return complextypetostring (scope, obj, VISITEDOBJS);
}
else {
Return (Scope + ": <already visited>/n");
}
}
else {
Return (Scope + ":" + obj.tostring () + "/n");
}
}
/**
* The typetostring () is used to dump the contents of a passed object
* of any type (or collection) to a String. This can is very useful for debugging code
* Manipulates complex structures.
*
* @param scope
* @param obj
*
* @return String
*
*/

public static string typetostring (string scope, Object obj) {

if (obj = = null) {
Return (Scope + ": null/n");
}
else if (Iscollectiontype (obj)) {
return collectiontypetostring (scope, obj, new ArrayList ());
}
else if (Iscomplextype (obj)) {
return complextypetostring (scope, obj, new ArrayList ());
}
else {
Return (Scope + ":" + obj.tostring () + "/n");
}
}
}

Related Article

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.