In the method below, I use reflection to set attributes of one class in another, based on annotation mapping. How do I map an attribute of a class that is an attribute of another?
For example, when using the following annotation: @Origin(field="modeloCarro.nome")
I want to access the attribute attribute name modeloCarro
.
/*
* Method should be implemented for copying non homonyms fields.
*
* @param T dto is the object that will receive the values.
*
* @param Object obj is the original object
*/
public void toDTOMappedFields(Object dto, Object obj) throws NoSuchFieldException, SecurityException, IllegalArgumentException, IllegalAccessException {
Class<?> classOriginal = (Class<?>) obj.getClass();
Class<?> classDTO = (Class<?>) dto.getClass();
for (Field fieldDTO : classDTO.getDeclaredFields()) {
if (fieldDTO.isAnnotationPresent(Origin.class)) {
Origin origin = fieldDTO.getAnnotation(Origin.class);
Field fieldOrigin = classOriginal.getDeclaredField(origin.field());
fieldOrigin.setAccessible(true);
fieldDTO.setAccessible(true);
fieldDTO.set(dto, fieldOrigin.get(obj));
}
}
}