« Back to profile of nawad980

  • Java

    toString Generator

    This method generates the toString descriptor of any object. Just pass it the object and it will read all the properties of the object using reflection and generate and appropriate String for you.

    15:34 Oct 03 2010 | Tags : toString,reflection,
    						public static String getToString(Object obj) {
  String sep = System.getProperty(""line.seperator"");

  StringBuffer sb = new StringBuffer();
  
  sb.append(obj.getClass().getName()).append("" :"").append(sep);
  
  Method[] methods = obj.getClass().getMethods();
  
  for (int i = 0; i < methods.length; i++) {
   Method method = methods[i];
   
   int prefixLen = 0;
   
   if (method.getName().startsWith(""get"")) {
    prefixLen = 3;
   } else if(method.getName().startsWith(""is"")) {
    prefixLen = 2;
   }//if
   
   if (prefixLen > 0 
     && method.getName().length() > prefixLen
     && method.getDeclaringClass().equals(obj.getClass())
     && method.getParameterTypes().length == 0) {
    
    sb.append(method.getName().substring(prefixLen)).append("" = "");
    
    try {
     sb.append(method.invoke(obj, null));
    } catch (Exception e) {     
    }//catch
    
    sb.append(sep);
   }//if
  }//for
  
  return sb.toString();
 }//getToString"
    			         
Add comment
To add a comment, please : Login or Sign up
    nawad980
    Nadeem Awad
  • New visitor?

    On setCode, you can save your codes, functions and classes, you can also share them with your friends, and track your favorite developer

    Join the SetCode community
  • Your language here :