Login | Register   
LinkedIn
Google+
Twitter
RSS Feed
Download our iPhone app
TODAY'S HEADLINES  |   ARTICLE ARCHIVE  |   FORUMS  |   TIP BANK
Browse DevX
Sign up for e-mail newsletters from DevX


Tip of the Day
Language: Java
Expertise: Intermediate
Apr 12, 2002

Write One toString() Method for Most All Your Classes

 
public String toString()
{
	StringBuffer sb = new StringBuffer( 256 );
	sb.append("[Field Name]\t[Value]\n");

	Class curr = this.getClass();
	while(curr != null){
		Field[] field = curr.getDeclaredFields();
		for(int i=0; i<field.length; ++i){
			sb.append( field[i].getName()+":\t" );
			try{
				sb.append
( "<"+field[i].get(this).toString()+">\n" );
			}
			catch(IllegalAccessException iae){
				sb.append
( "IllegalAccessException\n" );
			}
		}
		curr = curr.getSuperclass();			
//Recurse super classes
	}//end while
	return sb.toString();
}//end toString()
Tim Bauer
 
Comment and Contribute

 

 

 

 

 


(Maximum characters: 1200). You have 1200 characters left.

 

 

Sitemap
Thanks for your registration, follow us on our social networks to keep up-to-date