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

时间:2010-11-20 13:17:19

标签: 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.

    }

}

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

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

感谢。

2 个答案:

答案 0 :(得分:7)

在这个具体示例中,您可能正在寻找enum

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());

有关如何使用枚举的详细信息,请参阅Enum TypesThe Java Tutorials课程。

答案 1 :(得分:0)

定义static final int NOT_FOUND = 404, INTERNAL_SERVER_ERROR = 500;等常量或使用enum类型,而不是在代码中使用“magic constants”。