Generic toString()
Do you ever want a descriptive toString() of a class you just created, but don't feel like taking the time to write it? Here's a generic toString() that uses the java.lang.reflect package and will work in any class.
Note:
This isn't the end-all generic toString() method. It does the bare minimum of printing out each field and its value with the added ability to handle null values and arrays.
@Override
public String toString() {
Field[] fields = getClass().getDeclaredFields();
AccessibleObject.setAccessible(fields,true);
StringBuffer sb = new StringBuffer();
sb.append("Class: " + this.getClass().getName() + "\n");
for (Field field : fields) {
Object value = null;
try {
value = field.get(this);
} catch (IllegalAccessException e) {continue;}
sb.append("\tField \"" + field.getName() + "\"\n");
Class fieldType = field.getType();
sb.append("\t\tType: ");
if (fieldType.isArray()) {
Class subType = fieldType.getComponentType();
int length = Array.getLength(value);
sb.append(subType.getName() + "[" + length + "]" + "\n");
for (int i = 0; i < length; i ++) {
Object obj = Array.get(value,i);
sb.append("\t\tValue " + i + ": " + obj + "\n");
}
} else {
sb.append(fieldType.getName() + "\n");
sb.append("\t\tValue: ");
sb.append((value == null) ? "NULL" : value.toString());
sb.append("\n");
}
}
return sb.toString();
}
Example Output
Class: GenericToString
- Field "myint"
Type: int
Value: 9
- Field "myDouble"
Type: java.lang.Double
Value: 999.095
- Field "myString"
Type: java.lang.String
Value: My String
- Field "myNullObject"
Type: java.lang.Object
Value: NULL
- Field "myStringArray"
Type: java.lang.String[2]
Value 0: one
Value 1: two
- Field "myintArray"
Type: int[3]
Value 0: 1
Value 1: 2
Value 2: 3
- Field "myHashMap"
Type: java.util.HashMap
Value: {val3=3, val1=val1, val2=val2}
4 comments:
Great post. This could come in very handy. Have you noticed any performance degradation as you do this with more complex objects (ie. objects that have instances of other classes, which in turn have instances of other classes, etc)?
Very slick. I'll have to see about using this, probably fairly often
I created somethin similar for C# in my blog:
http://thorstenlorenz.blogspot.com/2009/06/after-reading-this-great-blog-by-rinat.html
The difference is that you have/get to decide which members of the class are going to be returned in the ToString() call.
cheapest uk supplier viagra viagra alternatives bought viagra fuerteventura non prescription viagra buy viagra on line homemade viagra cheapest viagra in uk how does viagra work buying viagra online viagra australia viagra generic soft tab buy viagra in canada buy viagra australia does viagra really work
Post a Comment