2

我目前正在做这样的事情;

import java.util.*;

public class TestHashMap {

    public static void main(String[] args) {

        HashMap<Integer, String> httpStatus = new HashMap<Integer, String>();
        httpStatus.put(404, "Not found");
        httpStatus.put(500, "Internal Server Error");

        System.out.println(httpStatus.get(404));    // I want this line to compile,
        System.out.println(httpStatus.get(500));    // and this line to compile.
        System.out.println(httpStatus.get(123));    // But this line to generate a compile-time error.

    }

}

我想确保在我的代码中到处都有 httpStatus.get(n),n 在编译时是有效的,而不是在运行时发现。这可以以某种方式强制执行吗?(我使用纯文本编辑器作为我的“开发环境”。)

我对 Java 很陌生(本周),所以请温柔一点!

谢谢。

4

2 回答 2

7

在这个特定示例中,您可能正在寻找一个枚举:

public enum HttpStatus {
  CODE_404("Not Found"),
  CODE_500("Internal Server Error");

  private final String description;

  HttpStatus(String description) {
    this.description = description;
  }

  public String getDescription() {
    return description;
  }
}

枚举是在 Java 中创建常量的一种便捷方式,由编译器强制执行:

// prints "Not Found"
System.out.println(HttpStatus.CODE_404.getDescription());

// prints "Internal Server Error"
System.out.println(HttpStatus.CODE_500.getDescription());

// compiler throws an error for the "123" being an invalid symbol.
System.out.println(HttpStatus.CODE_123.getDescription());

有关如何使用枚举的更多信息,请参阅The Java Tutorials中的Enum Types课程。

于 2010-11-20T13:20:29.640 回答
0

在代码中定义诸如此类static final int NOT_FOUND = 404, INTERNAL_SERVER_ERROR = 500;的常量或使用enum类型而不是使用“魔术常量”。

于 2010-11-20T13:22:47.210 回答