将枚举描述与可变参数组合在一起

时间:2016-11-14 17:52:09

标签: java enums

我有ENUM类,我使用它来构建响应对象,就像这样。

    if(statusCode == 0){
            userModel.setResponseCode(BOFAStatusCodes.ACTION_TAKEN.getErrorCode());
            userModel.setResponseMessage(BOFAStatusCodes.ACTION_TAKEN.getDescription());
        }

这是ENUM。

public enum BOFAStatusCodes {
ACTION_TAKEN(0,"An action has been taken that successfully completes the request."),
NO_ACTION(800,"No action was necessary to complete the request successfully."),
AUTH_FAILED(403,"Authentication failed."),
FAILURE_CLIENT(905,"The request cannot be completed due to an error with the client's request."),
FAILURE_SERVICE(500,"The request cannot be completed due to an error with the service's processing of the request.");

private String description;
private int errorCode;

private BOFAStatusCodes(int errorCode, String description){
    this.errorCode=errorCode;
    this.description = description;
}
public int getErrorCode() {
    return errorCode;
}

public String getDescription() {
    return description;
}

}

但现在要求是他们想要userID以及消息,例如:

An action has been taken that successfully completes the request for the User XXX.

任何建议。

1 个答案:

答案 0 :(得分:3)

您可以在枚举

中使用字符串格式
ACTION_TAKEN(0,"An action has been taken that successfully completes the request for the user %s.")

在你班上:

if(statusCode == 0){
        userModel.setResponseCode(BOFAStatusCodes.ACTION_TAKEN.getErrorCode());
        userModel.setResponseMessage(String.format(BOFAStatusCodes.ACTION_TAKEN.getDescription(), username));
    }