在java中我想生成编译时错误而不是运行时错误

Nig*_*ton 2 java hashmap compile-time

我现在正在做这样的事情;

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.

    }

}
Run Code Online (Sandbox Code Playgroud)

我想确保在我的代码中的任何地方都存在httpStatus.get(n),n在编译时是有效的,而不是在运行时稍后查找.这可以以某种方式强制执行吗?(我使用纯文本编辑器作为我的"开发环境".)

我是Java的新手(本周),所以请保持温和!

谢谢.

coo*_*ird 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;
  }
}
Run Code Online (Sandbox Code Playgroud)

枚举是一种在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());
Run Code Online (Sandbox Code Playgroud)

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