2016-04-10 21 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

這完全夠用了;但請注意[番石榴的'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);'這樣的東西。 –

相關問題