Last active
October 5, 2017 17:06
-
-
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.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* 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