mardi 29 juin 2021

Choosing which Enum to use dynamically in Java

I need to dynamically choose an Enum with some properties based on a parameter that will provide the suffix of the Enum name to use. I tried this but the "getCodigoAsString()" method doesn't work.

An Enum sample:

import lombok.AllArgsConstructor;
import lombok.Getter;

@AllArgsConstructor @Getter
public enum Chaves_35 {
    MODELO_DISPOSITIVO(1234,"TEXT","IN","Modelo Dispositivo"),
    DISPOSITIVO_SUPORTA_MULTI_TAREFA(4423,"TEXT","IN","Dispositivo Suporta Multi Tarefa"),
    NOME_DISPOSITIVO(7845,"TEXT","IN","Nome Dispositivo"),
    IDIOMA_DISPOSITIVO(3288,"TEXT","IN","Idioma Dispositivo"),
    ;

    private int codigo;
    private String tipo;
    private String fluxo;
    private String descricao;
  
    public String getCodigoAsString() {
        return String.valueOf(codigo);
    }
    
}

The Class that make the choice:

 public class ChavesCanal { 

    public static Enum<?>[] BuscaChavesCanal(int idCanal) {
        Enum<?>[] resp = null;

        switch (idCanal) {
            case 6:
                resp = Chaves_6.values();
                break;
            case 8:
                resp = Chaves_8.values();
                break;
            case 10:
                resp = Chaves_10.values();
                break;
            case 17:
                resp = Chaves_17.values();
                break;
            case 21:
                resp = Chaves_21.values();
                break;
            case 22:
                resp = Chaves_22.values();
                break;
            case 27:
                resp = Chaves_27.values();
                break;
            case 28:
                resp = Chaves_28.values();
                break;
            case 35:
                resp = Chaves_35.values();
                break;
            case 37:
                resp = Chaves_37.values();
                break;
            default:
                break;
        }

        return resp;
    }
}

This is the method that I'm trying to use the "ChavesCanal()" Class:

public static boolean VerificaChavesCanais_JSON(int codigoCanal) {
        if(codigoCanal <= 0) return false;
        
        try {           
            for (Enum<?> chaveId : ChavesCanal.BuscaChavesCanal(codigoCanal)) {
                if(!payloadJSON.has(chaveId.getCodigoAsString())) {
                    System.out.println("  .... chave '" + chaveId.getCodigoAsString() + "' não encontrada!!!");
                }
            }

            return true;

        } catch (Exception e) {
            System.out.println("ERRO em VerificaChavesCanais_JSON(): " + e.getMessage());
            return false;
        }
    }

Thanks folks!!!





Aucun commentaire:

Enregistrer un commentaire