2017-05-15 51 views
1

我有下面的代碼:如何操作錯誤代碼枚舉

public enum CpAutoExecCode implements CpAutoErrorCode { 
    //TODO - List of the execution error codes 
    //Error code sample 
    GENERIC_EXECUTION_ERROR(200,"Generic execution error code description"), 
    MISSING_REQUIRED_FIELD(201,"Required field %s is missing from model : %s"); 

    private final int number; 
    private final String description; 

    private CpAutoExecCode(int number,String description) { 
     this.number = number; 
     this.description = description; 
    } 

    @Override 
    public int getNumber() { 
     return number; 
    } 

    @Override 
    public String getDescription() { 
     return description; 
    } 
} 

我要分配在%S所需的字段和對象名稱。 有沒有人有一個簡單的方法來做到這一點?

回答

0

這真的取決於您對課程的使用情況。

舉例來說,如果你有一個自定義異常是發生在枚舉,你可以做這樣的事情:

class MyException { 

    int code; 

    MyException(CpAutoErrorCode error, Object[] args) { 
     super(format(error.getDescription(), args)); 
    } 

    private static String format(String error, Object[] args) { 
     // interpolate your string with the values 
    } 
} 

或者你也可以建立在枚舉類本身相同類型的結構。

1

您可以使用String.format()CpAutoExecCode.getDescription()

String formattedMessage = String.format(MISSING_REQUIRED_FIELD.getDescription(), 
           myMissingField, 
           myModel);