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

tester.one :

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));
     });
};
Kirill Simonov :

You could use functions in the following way:

@FunctionalInterface
interface CopyFunction<T> {
    T apply(T source, T result) throws Exception;
}

public static <T> CopyFunction<T> createCopyFunction(Class<T> type) {
    return (source, result) -> {
        for (Field field : getListOfFields(type)) {
            field.set(result, field.get(source));
        }
        return result;
    };
}

And then:

A a1 = new A(1, "one");
A a2 = new A(2, "two");
A result = createCopyFunction(A.class).apply(a1, a2);

The CopyFunction functional interface is pretty much the same as BinaryOperator except that BinaryOperator doesn't throw an exception. If you want to handle exceptions within a function, you can use the BinaryOperator instead.

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=461069&siteId=1