Olá, como esperado o teste não passou porque ele não habilita o id com set, o mesmo erro ocorre no vídeo, porém o teste do professor passou.
package br.com.alura.refl;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.util.Arrays;
public class Transformator {
public <I, O> O transform(I input) throws ClassNotFoundException, NoSuchMethodException, InvocationTargetException, InstantiationException, IllegalAccessException {
Class<?> source = input.getClass();
Class<?> target = Class.forName(source.getName() + "DTO");
O targetClass = (O) target.getDeclaredConstructor().newInstance();
Field[] sourceFields = source.getDeclaredFields();
Field[] targetFields = target.getDeclaredFields();
Arrays.stream(sourceFields).forEach(sourceField ->
Arrays.stream(targetFields).forEach(targetField -> {
validate(sourceField, targetField);
try {
targetField.set(targetClass, sourceField.get(input));
} catch (IllegalAccessException e) {
throw new RuntimeException(e);
}
}));
return targetClass;
}
private void validate(Field sourceField, Field targetField){
if(sourceField.getName().equals(targetField.getName()) && sourceField.getType().equals(targetField.getType())){
sourceField.setAccessible(true);
targetField.setAccessible(true);
}
}
}
package br.com.alura.refl;
import br.com.alura.Pessoa; import br.com.alura.PessoaDTO; import br.com.alura.PessoaService; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test;
import java.lang.reflect.InvocationTargetException;
public class TransformatorTest { Pessoa pessoa = new Pessoa(1, "João", "1234");
@Test
public void shouldTransform() throws ClassNotFoundException, InvocationTargetException, NoSuchMethodException, InstantiationException, IllegalAccessException {
Transformator transformator = new Transformator();
PessoaDTO pessoaDTO = transformator.transform(pessoa);
Assertions.assertInstanceOf(PessoaDTO.class, pessoaDTO);
Assertions.assertEquals(pessoa.getNome(), pessoaDTO.getNome());
Assertions.assertEquals(pessoa.getCpf(), pessoaDTO.getCpf());
}
}