Jun
24
Filed Under (Technology) by Thejesh GN on 24-06-2008

I have seen developers writing toString method in each of their bean class. The purpose is to print the bean variables for logging or debugging purposes. I thought of reducing their effort by writing a generic toString method to have in their base bean class. It works for simple bean classes. Its no-brainer you can modify to work for others.


public String toString() {
	String lineSeaparator = System.getProperty("line.separator");
	StringBuffer buffer = new StringBuffer(lineSeaparator);
	buffer.append("|---------");
	buffer.append(this.getClass());
	buffer.append("---------|");
	buffer.append(lineSeaparator);
	Method[] methods = this.getClass().getMethods();
	if(methods != null && methods.length >0){
		Method method = null;
		for(int i =0; i< methods.length; i++){
			method = methods[i];
			if(method.getName().startsWith("get")
			&& !method.getName().startsWith("getClass")){
			buffer.append
                                (method.getName().replaceAll("get",""));
			buffer.append(" = ");
			Object[] params=null;
			try {
				buffer.append
                                   (method.invoke(this, params));
			} catch (Exception e) {
				buffer.append("  ");
			}
				buffer.append(lineSeaparator);
			}
		}
	}
	buffer.append("|---------------------------------------------|");
	buffer.append(lineSeaparator);
	return buffer.toString();
}

Any suggestions to improve are welcome.



Comments:
3 Comments posted on "Generic toString Method for Simple Java Beans"
Veera on June 29th, 2008 at 11:03 pm

Does this method print only the variable names or variable names + values?

From the code, I think it prints only variable names. Is it correct?


Thejesh GN on June 29th, 2008 at 11:16 pm

It prints the values too. We are invoking the getter method using the reflection
method.invoke(this, params)
which returns the value.


Veerasundar on June 30th, 2008 at 11:49 am

Now I get it! :-)


Post a comment
Name: 
Email: 
URL: 
Comments: