Wednesday, December 23, 2009

Overriding the Java toString method using For loop

This solution uses a combination of reflection, constants and regular expressions to build a meaningful toString output:



private String TO_STRING_FIELDS = "email isPKI isTrustedRoot isITU_TX509 caName"

@Override public String toString() {
try {
StringBuilder result = new StringBuilder();
//String newLine = System.getProperty("line.separator");
String[] fieldList = TO_STRING_FIELDS.split( "[\\s,]+");
Field curField = null;
for (String f : fieldList) {
curField = this.getClass().getDeclaredField(f);
result.append(" " + f);
result.append(": ");
//requires access to private field:
result.append( curField.get(this) );
}
} catch (Exception e) {
System.out.println("Error in toString for class: " + this.getClass().getName() + "\n" + e.getMessage());
}

return null;
}

No comments: