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;
}