代码之家  ›  专栏  ›  技术社区  ›  Nigel Alderton

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

  •  2
  • Nigel Alderton  · 技术社区  · 14 年前

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

    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 回复  |  直到 14 年前
        1
  •  7
  •   Don Roby    14 年前

    在这个特定的例子中,它看起来像 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 Types 教训 The Java Tutorials .

        2
  •  0
  •   khachik    14 年前

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

    推荐文章