Java 8: how to use lambda expressions to copy the value of a selected field from one object to another

I'm trying to understand java 8's new functions: foreach and lambda expressions

Attempt to override this feature:

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;
}

Use lambda

I think it should be, but I can't make it right:

() -> {
     return getListOfFields(type).forEach((Field field) -> {
            field.set(result,field.get(source));
     });
};

Solution

You can use functions in the following ways:

@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;
    };
}

then:

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

The function interface of copyfunction is almost the same as that of binaryoperator, except that binaryoperator will not throw exceptions If you want to handle exceptions in a function, you can use binaryoperator

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>