开发者

In java I want to generate a compile-time error instead of a runtime error

I'm currently doing something like this;

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.

    }

}

I want to ensure that everywhere in my code that there is a httpStatus.get(n), that n is valid at compile-time rather than finding out later开发者_C百科 at runtime. Can this be enforced somehow? (I'm using a plain text editor as my "development environment".)

I'm very new to Java (this week) so please be gentle!

Thanks.


In this specific example, it seems like an enum is what you may be looking for:

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;
  }
}

An enum is a handy way of creating constants in Java, which are enforced by the compiler:

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

More information on how to use enums can be found in the Enum Types lesson from The Java Tutorials.


Define constants like static final int NOT_FOUND = 404, INTERNAL_SERVER_ERROR = 500; and so on or use enum types instead of using "magic constants" in your code.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜