4

I'm writing a custom deserializer for some json like data in my workplace, I have to set many values via setter methods and I want to only do that if they're not null.

Is there a nice way I can do this in Java by maybe passing the setter function as a parameter to another method?

i.e. Psuedo code:

private void setValue(Func setterMethod, <T> value){
    if (value != null){
        setterMethod(value);
    }
}
Kevin Workman
  • 41,537
  • 9
  • 68
  • 107
cg_
  • 329
  • 1
  • 4
  • 12
  • 1
    possible duplicate of [Java Pass Method as Parameter](http://stackoverflow.com/questions/2186931/java-pass-method-as-parameter) – Nir Alfasi Jun 24 '15 at 17:08
  • Not in a way that will not make your code a lot more unreadable. If you are deserializing by iterating through a map, why not check first if the value is not null, then make the decision which method to call? – RealSkeptic Jun 24 '15 at 17:45

3 Answers3

5

If your setter is a proper setter with returns void you must use a Consumer instead of a Function. This can only be used since Java 8.

private <T> void updateValue(Consumer<T> setterMethod, T value) {
    if (value != null){
        setterMethod.accept(value);
    }
}

This is usefull for partial updates. Example of use:

public Person partialUpdate(UUID id, Person update) {
    Person original = getPersonById(id);
    updateValue(original::setName, update.getName());
    updateValue(original::setAge, update.getAge());
    updateValue(original::setAddress, update.getAddress());
    return original;
}
Guest
  • 51
  • 1
  • 2
0

Since you're using generic it's not clear what is the domain of the function,
but assuming it's T -> T you can do something like:

private <T> void setValue(Function<T, T> setterMethod, T value){
    if (value != null){
        setterMethod.apply(value);
    }
}

That said, Java 6 does not supports it (Java 8 does).

Nir Alfasi
  • 53,191
  • 11
  • 86
  • 129
0

in java 6 you can define an interface like this

public interface Setter<T> {
    void set(T value);
}

and then implement your method this way

private <T> void setValue(Setter<T> setterMethod, T value){
    if (value != null){
        setterMethod.set(value);
    } 
}
Mohammad Alavi
  • 594
  • 6
  • 9