Skip to content

Instantly share code, notes, and snippets.

@m4nu56
Last active November 21, 2019 12:33
Show Gist options
  • Save m4nu56/8f74dc48e9e8eba07e7cc052db22761d to your computer and use it in GitHub Desktop.
Save m4nu56/8f74dc48e9e8eba07e7cc052db22761d to your computer and use it in GitHub Desktop.
Map the fields of a class into a Map with fieldName and fieldValue
import org.apache.commons.lang3.tuple.Pair;
import java.lang.reflect.Field;
import java.lang.reflect.Modifier;
import java.util.Map;
import java.util.stream.Collectors;
import java.util.stream.Stream;
public class ReflectionClassFields {
public Map<String, Object> mapClassFieldsValues(Object entity) throws IllegalArgumentException {
Stream<Field> declaredFields = Stream.of(entity.getClass().getDeclaredFields());
return declaredFields
.collect(Collectors.toMap(
Field::getName,
field -> {
try {
return Pair.of(field.getName(), getFieldValue(entity, field));
} catch (IllegalAccessException e) {
throw new RuntimeException(e);
}
}
));
}
private Object getFieldValue(Object entity, Field field) throws IllegalAccessException {
if (Modifier.isPrivate(field.getModifiers())) {
field.setAccessible(true);
}
return field.get(entity);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment