Last active
October 3, 2017 06:35
-
-
Save jdesive/43f7ed2f84fa522955b35e6775fbc7c9 to your computer and use it in GitHub Desktop.
Dynamic toString method that excludes null values
This file contains hidden or 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
@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(); | |
} |
This file contains hidden or 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
@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