2
respostas

[Dúvida] IllegalAccessException: Não deixa criar Objeto Pessoa

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.

Insira aqui a descrição dessa imagem para ajudar na acessibilidade

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());

}

}

2 respostas

Encontrei meu erro.

no bloco try/catch tenho que so dar um print e não lançar exceção.

Bom dia, Caio! Tudo bem?

Fico feliz que tenha resolvido o problema que estava tendo! Além disso, agradeço por compartilhar a causa do problema, pois, o mesmo pode acontecer com outros estudantes e seu post poderá ajudar.

No mais, bons estudos!