4
In the method below, I use Reflection to set attributes from one class to another, based on mapping via Annotation. 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 name attribute 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));
}
}
}
Thank you for the answer, it is very close to what I need, once I have the code with the solution I will post.
– Mayllon Baumer