6

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?

Sebi
  • 2,534
  • 2
  • 26
  • 28
  • 1
    For what purpose? It's easier to do that in the corresponding get() method, if you always call it, than it is to affect the actual value. – user207421 Nov 28 '11 at 09:05
  • The classes are generated by JAXB2, so I don't want to change them. – Sebi Nov 28 '11 at 09:13
  • If you are using an `.xsd` to define the schema for JAXB2 you can define `default` values direct in the `.xsd`. – ante Nov 28 '11 at 09:32
  • Unfortunately the schema is not under my control.. But I agree that it would be better to solve the problem there. – Sebi Nov 28 '11 at 09:54

5 Answers5

7
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, "");
            }
        }
    }
}
seanxiaoxiao
  • 1,282
  • 2
  • 11
  • 23
1

You can use reflection to list all fields of an object and then check and change it. You might have to modify the access level, if they are private. You can find a lot of tutorials on that when searching Google, e.g. this one.

Till Helge
  • 9,253
  • 2
  • 40
  • 56
1

Try to use AspectJ:

@Aspect
public class StringHandler {
    @Around("execution(String com....YourClass.*(*))")
    public Object handle(ProceedingJoinPoint thisJoinPoint) throws Throwable {   
        String s = (String) thisJoinPoint.proceed();
        if (s == null){
           return "";
        }
        return s;
    }
}

This will be faster in run-time because this aspect will be compiled to byte-code, otherwise reflection will be used at run-time and slows your app.

Stanislav Levental
  • 2,165
  • 1
  • 14
  • 28
0

Another way is to write an utility which generates code which sets empty strings to members of particular objects.

Lavir the Whiolet
  • 1,006
  • 9
  • 18
0

In favor of reusable design you should consider using a default value for null values just like Apache's common defaultString API, something like this:

public String getValue(String value){
   return StringUtils.defaultString(value);
}

You can also consider using defaultString(String str,String defaultStr) so that you have the option of changing the default value to anything should there be any reason of doing so.

StringUtils documentation

mprabhat
  • 20,107
  • 7
  • 46
  • 63