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.


 
4 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! :-)


Guido on May 30th, 2009 at 1:39 PM #

Nice code snippet. But it does not work with boolean properties.
This is how you can add boolean props:
for (int i = 0; i < methods.length; i++) {
method = methods[i];
final String methodName = method.getName();
final boolean isBooleanProp = methodName.startsWith(“is”);
if ((methodName.startsWith(“get”) || isBooleanProp) && !method.getName().startsWith(“getClass”)) {
buffer.append(method.getName().replaceAll(isBooleanProp ? “is” : “get”, “”));
buffer.append(” = “);
Object[] params = null;
try {
buffer.append(method.invoke(this, params));
} catch (Exception e) {
buffer.append(” “);
}
buffer.append(lineSeaparator);
}
}


Post a comment
   Name Required
   Email Required
   URL