我正在尝试理解
java8的新函数:forEach和lambda表达式.
试图重写这个功能:
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;
}
使用lambda.
我认为它应该是这样的,但不能使它正确:
() -> {
return getlistofFields(type).forEach((Field field) -> {
field.set(result,field.get(source));
});
};
解决方法
您可以通过以下方式使用函数:
@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;
};
}
然后:
A a1 = new A(1,"one"); A a2 = new A(2,"two"); A result = createcopyFunction(A.class).apply(a1,a2);
copyFunction功能接口与BinaryOperator几乎相同,只是BinaryOperator不会抛出异常.如果要处理函数中的异常,可以使用BinaryOperator.