I want to set all String members of an object to an empty string if they are null.
Pseudocode:
foreach member in object {
if (member instanceof String and member == null) {
member = '';
}
}
What is the simplest way to achieve that? Any framework / tool that I can use? Write my own solution via reflection?
To initialize an empty string in Python, Just create a variable and don't assign any character or even no space. This means assigning “” to a variable to initialize an empty string.
Initializing a string variable to null simply means that it does not point to any string object. String s=null; Whereas initializing a string variable to “” means that the variable points to an object who's value is “”.
So in your code, you can use: private static final String[] EMPTY_ARRAY = new String[0];
public static void setEmpty(Object object) throws IllegalArgumentException, IllegalAccessException {
Class<?> clazz = object.getClass();
Field[] fields = clazz.getDeclaredFields();
for (Field field : fields) {
if (String.class.equals(field.getType())) {
field.setAccessible(true);
if (field.get(object) == null) {
field.set(object, "");
}
}
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With