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

I am trying to understand the 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 cannot do it right:

 () -> { return getListOfFields(type).forEach((Field field) -> { field.set(result, field.get(source)); }); }; 
+7
java lambda java-8
source share
2 answers

You can use functions as follows:

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

CopyFunction functional interface is CopyFunction much the same as BinaryOperator , except that BinaryOperator does not BinaryOperator an exception. If you want to handle exceptions inside a function, you can use BinaryOperator .

+1
source share

The cycle can be replaced by

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

However, calling the forEach method has no return value, so you still need to

 return result; 

separately.

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 did not notice this problem with an exception. You will have to catch the exception and throw the 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; } 
+5
source share

All Articles