0

I'm working on an API (Eclipse IDE - Kepler), JDK 1.7) I need a shortcut like @IfNotNullUpdate

consider the following e.g.

Model model = new Model();
String field1 = entity.getField1() != null ? entity.getField1() : "";
model.setField1(field1);

so that I can simply write it like

model.setField1( @IfNotNullUpdate entity.getField1(),"");

I don't want to have any NullPointerExceptions. It will be a great help If it can work like builder pattern. for e.g.

model.addField_25(@IfNotNullUpdate entity.getField_37())
     .addField_16(@IfNotNullUpdate entity.getField_69());

I tried @NonNull of lombok. It just ensures that param is not null which is not my requirement.

And of-course assert() can't be a solution. Hope I'm able to explain my requirement well.

Thanks in advance.

  • possible duplicate of [How to handle null string in java](http://stackoverflow.com/questions/22902705/how-to-handle-null-string-in-java) – Rajat Sep 02 '15 at 04:04
  • It is not a duplicate. He likes to know if there is an existing solution for auto setting the values. – Karthik R Sep 02 '15 at 04:18
  • This might help: http://stackoverflow.com/questions/271526/avoiding-null-statements-in-java – Zarwan Sep 02 '15 at 04:25

4 Answers4

1

Have a look at Optional. Using the sample provided, the following can throw a NPE if any of the methods called returns a null value:

String version = computer.getSoundcard().getUSB().getVersion();

To avoid that or excessive if (x != null) checks, using Optional you can use:

String name = computer.flatMap(Computer::getSoundcard)
                          .flatMap(Soundcard::getUSB)
                          .map(USB::getVersion)
                          .orElse("UNKNOWN");
M. Shaw
  • 1,742
  • 11
  • 15
0

Why don't you use just a method? You can make it static if you want, so that you can access it by className. Or put your helper methods that you need in oneClass and extend it.

public String getFieldValue(Object o ){
    if(o instanceof someEntity){
        someEntity se = (someEntity) o
        if(someEntity.getField() != null){
            return someEntity.getField();
        }else{
            return ""; 
        }
    }else if(o instanceof someOtherEntity){
       ...
    }
}
rone
  • 67
  • 1
  • 7
  • Is this practically viable if i have some thousands of entities and models each with hundreds of fields? – D V Santhosh Kiran Sep 02 '15 at 05:51
  • guess not if you have many of them. Then you can use reflection: – rone Sep 02 '15 at 06:39
  • `Public String getField(Object bean, String methodName){ BeanInfo info = Introspector.getBeanInfo(bean.getClass(), Object.class); PropertyDescriptor[] props = info.getPropertyDescriptors(); String value; for (PropertyDescriptor pd : props) { Method getter = pd.getReadMethod(); if(getter.getName().equals(methodName)){ //add try catch //get the value from method value = getter.invoke(bean); if(value != null)return value; } } return ""; }` – rone Sep 02 '15 at 07:01
0

You would need to build a custom annotation for this or any purpose of yours. You can create an Annotation for you with @Target(ElementType.PARAMETER) and sue reflection to map it as required. But this is so lengthy process which doesn't need much of your time. Instead just write a method and just call it.

I can't think of an API readily available. As you pointed out, lombok doesn't do that for you.

Karthik R
  • 5,523
  • 2
  • 18
  • 30
0

Updating answer with JDK17:

I have a helper method like

public class NpeHelper {
 public static <T> Optional<T> ofNullable(final Supplier<T> resolver) {
        try {
            final T result = resolver.get();
            return Optional.ofNullable(result);
        } catch (NullPointerException e) {
            return Optional.empty();
        }
    }
}

I can use this helper function as

model.addField_25(NpeHelper.ofNullable(()-> entity.getField_37()).orElse(<AnyObject<));

For Nullable streams validation I'm using ApacheCommons' CollectionUtils.emptyIfNull();