Friday, January 8, 2010

public String toString()

I was writing a simply toString() implementation today to easy my view of an object when debugging. After I was done, I thought, why isn't this standard in all objects?


public String toString(){
try{
Method[] methods = this.getClass().getMethods();
Object[] arguments = {};
for(int x=0;x<methods.length;x++){
Method nextMethod = methods[x];
if(nextMethod.getName().startsWith("get")){
Object value = nextMethod.invoke(this,arguments);
buffer.append(nextMethod.getName());
buffer.append("=");
buffer.append(value);
buffer.append("|");
}
}
} catch (Exception e) {
// do something
}

return buffer.toString();
}


The basic point is to simply show the values on the object via the getters. Seems to be useful.

No comments:

Share on Twitter