Home > Back-end >  How to dynamic formating Enum label at runtime
How to dynamic formating Enum label at runtime

Time:12-21

I created a custom Enum type for error handling with two variables code and label, and I would like the value of the label property of the enum to be formatted at runtime using like String.format(key, value)

`

public enum CustumErrorEnum{
    MISSING_VALUE1("CODE1","the label %s is missing"),
    WRONG_VALUE1("CODE2","the label %s is wrong");
    
    private String code;
    private String label;
    
    CustumErrorEnum(String code, String label){
        this.code = code;
        this.label = label;
    }
    
}

`

I am trying to customise log by specifying the raison and the value that throw the exception

e.g when user field a wrong for example, I need the output to be : W001, The value 2026-13-13 is wrong

CodePudding user response:

You can use String.format method.

public static String finalMsg(final CustumErrorEnum custumErrorEnum, Object... args) {
        final String formattedMsg = String.format(custumErrorEnum.label, args);
        return custumErrorEnum.code   ","   formattedMsg;
    }

Complete applicaiton is given below.

public class App {

    private static enum CustumErrorEnum {
        MISSING_VALUE1("CODE1", "the label %s is missing"), WRONG_VALUE1("CODE2", "the label %s is wrong");

        private String code;
        private String label;

        CustumErrorEnum(String code, String label) {
            this.code = code;
            this.label = label;
        }

    }

    public static String finalMsg(final CustumErrorEnum custumErrorEnum, Object... args) {
        final String formattedMsg = String.format(custumErrorEnum.label, args);
        return custumErrorEnum.code   ","   formattedMsg;
    }

    public static void main(String[] args) {
        System.out.println(finalMsg(CustumErrorEnum.MISSING_VALUE1, "city"));
    }

}

CodePudding user response:

For adding Values inside a String you can do:

String error = "W001, The Value "   variable   " is wrong"

In combination with your enum, if you get a String than create a new one like

String error = yourString.subString(index1,index2)   variables   sourString.subString(index3, index4);
  • Related