Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java8: how to copy values of selected fields from one object to other using lambda expression

I'm trying to understand new functions of java8: forEach and lambda expressions.

Trying to rewrite this function:

public <T extends Object> T copyValues(Class<T> type, T source, T result)
        throws IllegalAccessException
{
    for(Field field : getListOfFields(type)){
        field.set(result, field.get(source));
    }
    return result;
}

using lambda.

I think it should be something like this but can't make it right:

() -> {
     return getListOfFields(type).forEach((Field field) -> {
            field.set(result, field.get(source));
     });
};
like image 801
tester.one Avatar asked Feb 20 '18 14:02

tester.one


1 Answers

The loop can be replaced by

getListOfFields(type).forEach((field) -> field.set(result, field.get(source)));

However, that forEach method call has no return value, so you still need to

return result;

separately.

The full method:

public <T extends Object> T copyValues(Class<T> type, T source, T result)
        throws IllegalAccessException
{
    getListOfFields(type).forEach((field) -> field.set(result, field.get(source)));
    return result;
}

EDIT, I didn't notice the issue with the exception. You'll have to catch the exception and throw some unchecked exception. For example:

public <T extends Object> T copyValues(Class<T> type, T source, T result)
{
    getListOfFields(type).forEach (
      (field) -> {
        try {
            field.set(result, field.get(source));
        } catch (IllegalAccessException ex) {
            throw new RuntimeException (ex);
        }
    });
    return result;
}
like image 180
Eran Avatar answered Sep 23 '22 00:09

Eran