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}