我在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]
。
答案 0 :(得分:2)
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
而不是数字代码。如果你需要通过代码真正获得值,只需添加一个静态方法来解析枚举实例。
答案 1 :(得分:1)
您可以使用静态类初始化程序并使用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"
static{
HashMap<Integer,String> statusValues=new HashMap<>();
statusValues.put(200,"OK");
statusValues.put(201,"Created");
// ...
STATUS=Collections.unmodifiableMap(statusValues);
}