newbie newbie - 2 years ago 110
Java Question

Is it possible in Java to check if objects fields are null and then add default value to all those attributes?

I need to make sure that no object attribute is null and add defautl value in case if it is null. Is there any easy way to do this, or do I have to do it manually by cheking every attrute by its getter and setters?

Answer Source

You can use reflection to iterate over the object's field, and set them. You'd obviously need some sort of mapping between types or even field names and required default values but this can be done quite easily in a loop. For example:

for (Field f : obj.getClass().getFields()) {
  if (f.get(obj) == null) {
     f.set(obj, getDefaultValueForType(f.getType()));
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download