Skip to content

Instantly share code, notes, and snippets.

@dasniko
Created September 25, 2019 11:13
Show Gist options
  • Save dasniko/70d51437f9c36ecb6907cd372ac53e3b to your computer and use it in GitHub Desktop.
Save dasniko/70d51437f9c36ecb6907cd372ac53e3b to your computer and use it in GitHub Desktop.
package dasniko.util;
import java.lang.reflect.Field;
import java.lang.reflect.Modifier;
/**
* @author Niko Köbler, https://www.n-k.de, @dasniko
*/
public class ToStringUtil {
public static String toString(Object object) {
if (object == null) return "null";
Class<?> clazz = object.getClass();
StringBuilder sb = new StringBuilder(clazz.getSimpleName()).append("(");
while (clazz != null && !clazz.equals(Object.class)) {
Field[] fields = clazz.getDeclaredFields();
for (Field f : fields) {
if (!Modifier.isStatic(f.getModifiers())) {
try {
f.setAccessible(true);
sb.append(f.getName()).append("=").append(f.get(object)).append(", ");
} catch (IllegalAccessException e) {
e.printStackTrace();
}
}
}
clazz = clazz.getSuperclass();
}
sb.deleteCharAt(sb.lastIndexOf(", "));
return sb.append(")").toString();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment