這個(gè)系列,結(jié)合IDEA的Inspection和我自己的理解編寫。
抽象問(wèn)題
1. 把實(shí)例造型(cast)成具體的類型
這個(gè)問(wèn)題的含義是,當(dāng)?shù)玫揭粋€(gè)實(shí)例時(shí),把它c(diǎn)ast到一個(gè)更加具體的類型使用。這個(gè)問(wèn)題存在于以下場(chǎng)景:
public Collection aMethod(Collection c) {
List list = (List)c;
Object o = list.get(0); // Collection中沒有g(shù)et方法。導(dǎo)致實(shí)現(xiàn)者必須cast。
...
}
public void test() {
// 返回值必須cast才能使用更加具體的方法。
List alist = (List)aMethod(Arrays.asList(new String[]{"1", "2"}));
Object obj = alist.get(0);
...
}
public someMethod() {
MyInterface mi = new MyImplementation();
...
// 大部分時(shí)間調(diào)用MyInterface中的方法,但忽然發(fā)現(xiàn)有某個(gè)地方需要調(diào)用特定的非接口實(shí)現(xiàn):
int count = ((MyImplementation)mi).specialMethod();
...
}
最后這個(gè)例子,可能是方法的實(shí)現(xiàn)本身的問(wèn)題,比如完全可以直接使用MyImplementation來(lái)定義變量mi;也可能是抽象問(wèn)題,即沒有把本來(lái)具有普遍性的方法放到接口中,而是放到了具體實(shí)現(xiàn)中。
public boolean equals(Object o) {
if (o == null) return false;
if (o instanceof MyClass) { // 安全檢查!
MyClass mc = (MyClass)o;
// 調(diào)用MyClass中的特定方法。
...
}
public method() {
Collection c = aMethodReturnsCollection();
List list = new ArrayList(c); //安全的類型轉(zhuǎn)換,把Collection轉(zhuǎn)換成List。
...
}
抽象問(wèn)題
1. 把實(shí)例造型(cast)成具體的類型
這個(gè)問(wèn)題的含義是,當(dāng)?shù)玫揭粋€(gè)實(shí)例時(shí),把它c(diǎn)ast到一個(gè)更加具體的類型使用。這個(gè)問(wèn)題存在于以下場(chǎng)景:
- 出于個(gè)人原因,比如只熟悉這個(gè)具體的類型、不動(dòng)腦筋的編碼。
- 需要的方法不在更抽象的類型中,只在具體類型中才有定義。
public Collection aMethod(Collection c) {
List list = (List)c;
Object o = list.get(0); // Collection中沒有g(shù)et方法。導(dǎo)致實(shí)現(xiàn)者必須cast。
...
}
public void test() {
// 返回值必須cast才能使用更加具體的方法。
List alist = (List)aMethod(Arrays.asList(new String[]{"1", "2"}));
Object obj = alist.get(0);
...
}
public someMethod() {
MyInterface mi = new MyImplementation();
...
// 大部分時(shí)間調(diào)用MyInterface中的方法,但忽然發(fā)現(xiàn)有某個(gè)地方需要調(diào)用特定的非接口實(shí)現(xiàn):
int count = ((MyImplementation)mi).specialMethod();
...
}
最后這個(gè)例子,可能是方法的實(shí)現(xiàn)本身的問(wèn)題,比如完全可以直接使用MyImplementation來(lái)定義變量mi;也可能是抽象問(wèn)題,即沒有把本來(lái)具有普遍性的方法放到接口中,而是放到了具體實(shí)現(xiàn)中。
- 受環(huán)境約束,必須安全的使用造型。
public boolean equals(Object o) {
if (o == null) return false;
if (o instanceof MyClass) { // 安全檢查!
MyClass mc = (MyClass)o;
// 調(diào)用MyClass中的特定方法。
...
}
public method() {
Collection c = aMethodReturnsCollection();
List list = new ArrayList(c); //安全的類型轉(zhuǎn)換,把Collection轉(zhuǎn)換成List。
...
}