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; }
Eran
source share