Skip to content

Instantly share code, notes, and snippets.

@jdesive
Last active October 3, 2017 06:35
Show Gist options
  • Save jdesive/43f7ed2f84fa522955b35e6775fbc7c9 to your computer and use it in GitHub Desktop.
Save jdesive/43f7ed2f84fa522955b35e6775fbc7c9 to your computer and use it in GitHub Desktop.
Dynamic toString method that excludes null values
@Override
public String toString(){
StringBuilder stringBuilder = new StringBuilder(this.getClass().getSimpleName()).append("[ ");
Arrays.stream(getClass().getDeclaredFields()).filter(field -> {
field.setAccessible(true);
try {
Object value = field.get(this);
if(value != null)
return true;
} catch (IllegalAccessException e) {}
return false;
}).forEach(field -> {
try {
stringBuilder.append(field.getName()).append("=").append(field.get(this)).append(" ");
} catch (IllegalAccessException e) {
e.printStackTrace();
}
});
return stringBuilder.append("]").toString();
}
@Override
public String toString(){
StringBuilder stringBuilder = new StringBuilder(this.getClass().getSimpleName()).append("[ ");
for(Field field : getClass().getDeclaredFields()){
try {
field.setAccessible(true);
Object value = field.get(this);
if(value != null)
stringBuilder.append(field.getName()).append("=").append(field.get(this)).append(" ");
} catch (IllegalAccessException e) {
e.printStackTrace();
}
}
return stringBuilder.append("]").toString();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment