Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Initialize all String members with an empty String

Tags:

java

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?

like image 273
Sebi Avatar asked Nov 28 '11 08:11

Sebi


People also ask

How do you initialize an empty string?

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.

Can we initialise string with null?

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 “”.

How do you initialize a string array to an empty string in Java?

So in your code, you can use: private static final String[] EMPTY_ARRAY = new String[0];


1 Answers

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, "");
            }
        }
    }
}
like image 185
seanxiaoxiao Avatar answered Nov 05 '22 16:11

seanxiaoxiao