我在我的Go程序中有一个类似的变量,并试图像在Java中那样做;
var (
STATUS = map[int]string{
200: "OK",
201: "Created",
202: "Accepted",
304: "Not Modified",
400: "Bad Request",
401: "Unauthorized",
403: "Forbidden",
404: "Not Found",
405: "Resource Not Allowed",
406: "Not Acceptable",
409: "Conflict",
412: "Precondition Failed",
415: "Bad Content Type",
416: "Requested Range Not Satisfiable",
417: "Expectation Failed",
500: "Internal Server Error",
}
)我尝试使用HashMap或其他数组内容,但不能使用,因为它将是Response类的属性,必须在开始时定义,如;
package http;
class Response {
// here define filling it e.g STATUS = new Array(200, "OK", ...) etc..
... STATUS ...
}是的,我可以使用HashMap在构造函数中填充它,但是我不能像这样得到例如"OK“:String status = STATUS[200]。
发布于 2016-08-19 07:52:50
enum最适合:
public enum Response {
OK(200, "OK"),
Created(201, "Created"),
NotFound(404, "Not found");
private final int _code;
private final String _message;
Response(int code, String message) {
_code = code;
_message = message;
}
public int code() {
return _code;
}
public String message() {
return _message;
}
}枚举的另一个好处是,您可以在代码中使用可理解的常量名称进行操作,例如Response.NotFound,而不是数字代码。如果您真的需要通过代码获取一个值,只需添加一个静态方法来解析枚举实例。
发布于 2016-08-19 07:52:38
您可以使用静态类初始化器并使用HashMap,就像您尝试过的那样。
class Response
{
public static final Map<Integer,String> STATUS;
static{
STATUS=new HashMap<>();
STATUS.put(200,"OK");
STATUS.put(201,"Created");
// ...
}
}示例用法:
Response.STATUS.get(200); // will return "OK"如果您愿意,您甚至可以使用Collection.unmodifiableMap()使其不可修改。这就是我要做的。所以上面的静态类初始化器现在看起来像这样:
static{
HashMap<Integer,String> statusValues=new HashMap<>();
statusValues.put(200,"OK");
statusValues.put(201,"Created");
// ...
STATUS=Collections.unmodifiableMap(statusValues);
}https://stackoverflow.com/questions/39029088
复制相似问题