Skip to content

Instantly share code, notes, and snippets.

@banasiak
Last active October 5, 2017 17:06
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save banasiak/3bcb39ad7747e1c360db1a88c698ecad to your computer and use it in GitHub Desktop.
Save banasiak/3bcb39ad7747e1c360db1a88c698ecad to your computer and use it in GitHub Desktop.
Create a string representation of an object. This will include all fields that are not transient or static. The returned string will be in the form of `full_class_name{fieldName='value'}` This will also include all super types values as well in the string.
/**
* Create a string representation of an object. This will include all fields that are not
* transient or static. The returned string will be in the form of `full_class_name{fieldName='value'}`
* This will also include all super types values as well in the string.
*
* @param object The object to get a string representation from.
* @return String representation of the object.
*/
public static String toString(Object object) {
Class<?> aClass = object.getClass();
StringBuilder stringBuilder = new StringBuilder(aClass.getName());
stringBuilder.append("{");
for (; aClass != null; aClass = aClass.getSuperclass()) {
Field[] declaredFields = aClass.getDeclaredFields();
for (Field declaredField : declaredFields) {
declaredField.setAccessible(true);
int modifiers = declaredField.getModifiers();
if (Modifier.isTransient(modifiers) || Modifier.isStatic(modifiers)) {
continue;
}
Object field;
try {
field = declaredField.get(object);
stringBuilder.append(declaredField.getName())
.append("='")
.append(String.valueOf(field))
.append("', ");
} catch (IllegalAccessException ignore) {
// Don't care, just continue trying to create the string.
}
}
}
// remove the last "', "
stringBuilder.delete(stringBuilder.length() - 3, stringBuilder.length());
stringBuilder.append("}");
return stringBuilder.toString();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment