Access method of type String with Reflection

Asked

Viewed 26 times

2

I have the following class of Enum:

public enum Teste {

    TESTE( 101, "Teste" ), 
    MUNDO( 601, "Mundo" ); 
    

    private final String descricao;
    private final int codigo;

    Teste( int codigo, String descricao ) {
        this.descricao = descricao;
        this.codigo = codigo;
    }

    public String getDescricao() {
        return descricao;
    }

    public int getCodigo() {
        return codigo;
    }

}

I am trying to access enums attributes using Reflection:

String classe = "br.com.test.Teste";
Class<?> cls = Class.forName( classe );

Object[] listaEnum = cls.getEnumConstants();

for( Object enumsL : listaEnum ) {

        enumDto = new IndiceReajusteEnumDTO();
        enumDto.setId( enumsL.toString() );
        Method mtDescricao = cls.getDeclaredMethod( "getDescricao" );
        mtDescricao.setAccessible( true );
        String valorDescricao = ( String ) mtDescricao.invoke( cls.newInstance() );
        enumDto.setDescricao( valorDescricao );
        enumDto.setCodigo( cls.getMethod( "getCodigo" ).toGenericString() );            

        enumsArray.add( enumDto );
    }

Along those lines String valorDescricao = ( String ) mtDescricao.invoke( cls.newInstance() );

the following exception occurs:

 java.lang.NoSuchMethodException: br.com.Teste.<init>()
 java.lang.InstantiationException: br.com.Teste

If necessary, follow the DTO:

@AllArgsConstructor
@NoArgsConstructor
@Getter
@Setter
public class IndiceReajusteEnumDTO {

    private String id;
    private String descricao;
    private String codigo;

}

1 answer

2


The problem was here when calling the invoke method, was restarting the instance and actually needed to pass as parameter my object.

String valorDescricao = ( String ) mtDescricao.invoke( cls.newInstance() );

for

String valorDescricao = ( String ) mtDescricao.invoke( enumL );

Browser other questions tagged

You are not signed in. Login or sign up in order to post.