2010-11-20 91 views
2

我目前正在做这样的事情;在java中,我想生成一个编译时错误,而不是运行时错误

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(本周)很新,所以请温柔!

谢谢。

回答

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

有关如何使用枚举的更多信息,请参见课程The Java Tutorials

+1

枚举常量必须是标识符,所以你必须使用名称,如“r404”和“r500”(或类似的东西)。 – Pointy 2010-11-20 13:25:57

+0

@点好看!感谢您指出了这一点! – coobird 2010-11-20 13:26:57

+0

+1:但我编辑过,以保持一致。 – 2010-11-20 13:42:49

0

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

相关问题