2016-04-10 1 views
0

は、我々は次のコードしているとしましょう場合は、別のオブジェクトを確認する方法を作成します。ヌルスロー例外

public void a(String a) { 
    if (a == null) { 
     throw new IllegalArgumentException(); 
    } 
} 

public void b(Queue<Integer> b) { 
    if (b == null) { 
     throw new IllegalArgumentException(); 
    } 
} 

public void c(Stack<Integer> c) { 
    if (c == null) { 
     throw new IllegalArgumentException(); 
    } 
} 

をスロー新しい例外ジョブ を行う方法を記述することが可能ですか?パラメータのそれらの型が同じでないこと

public void a(String a) { 
    check(a); 
} 

public void b(Queue<Integer> b) { 
    check(b); 
} 

public void c(Stack<Integer> c) { 
    check(c); 
} 

お知らせ:それはこのようなものです。あなたはより一般的なようにすることができ

+1

'無効チェック(オブジェクトo){ 場合(O == NULL){ スロー新しい例外:IllegalArgumentException(); } }「 ? –

答えて

1

public void check(Object a) { 
    if (a == null) { 
     throw new IllegalArgumentException(); 
    } 
} 
+0

これは完全に適切です。しかし、どのように[Guavaの 'Preconditions.checkNotNull'](http://grepcode.com/file/repo1.maven.org/maven2/com.google.guava/guava/19.0-rc1/com/google/common/base/)に注意してください。 Preconditions.java/#210)はジェネリックで実装されているので、 'this.a = check(a);'のようなものを書くことができます。 –

関連する問題