2

私は現在、このようなことをしています。

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(今週)が初めてなので、優しくしてください!

ありがとう。

4

2 に答える 2

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

列挙型は、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());

列挙型の使用方法の詳細については、Java チュートリアルの列挙型のレッスンを参照してください。

于 2010-11-20T13:20:29.640 に答える
0

などの定数を定義するstatic final int NOT_FOUND = 404, INTERNAL_SERVER_ERROR = 500;enum、コードで「魔法の定数」を使用する代わりに型を使用します。

于 2010-11-20T13:22:47.210 に答える