2010-11-20 10 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ように思えるあなたが探してすることができるものです:列挙型は、コンパイラによって強制されたJavaで定数を作成するための便利な方法です

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

// 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にあります。

+1

列挙定数は識別子でなければならないので、 "r404"や "r500"(またはそのような名前)のような名前を使用する必要があります。 – Pointy

+0

@Pointyナイスキャッチ!それを指摘してくれてありがとう! – coobird

+0

+1:しかし、あなたのために一貫性を持たせるために編集しました。 –

0

static final int NOT_FOUND = 404, INTERNAL_SERVER_ERROR = 500;などの定数を定義するか、コードに "magic constant"を使用する代わりにenumタイプを使用してください。

関連する問題