Last active
November 21, 2019 12:33
-
-
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
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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