這是jdk1.5一個(gè)已經(jīng)報(bào)告的bug:
http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=5103041
問題在于在jdk1.5中Timestamp多定義了一個(gè)比較方法:
public int compareTo(java.util.Date o) {
return compareTo((Timestamp)o);
}
這樣如樓主所說,在1.4中Timestamp.compareTo(Date)的時(shí)候會調(diào)用繼承來的Date.compareTo(Date)方法來完成比較,而Date.compareTo(Date)在比較前會把參數(shù)造型成Date對象,因此可以完成比較;而在1.5中Timestamp則直接使用自己的Timestamp.compareTo(Date)方法來比較,并試圖在其中把參數(shù)造型成Timestamp,因此拋出造型異常。
但是這并不像樓主想像的,“Generics也會帶來一些其他的問題”,而是sun有意為之。看上面這個(gè)compareTo方法的相關(guān)說明:
// This forwarding method ensures that the compareTo(Date) method defined
// in java.util.Date is not invoked on a Timestamp
顯然sun認(rèn)為1.4中的做法是不對的,下定決心在以放棄兼容性為代價(jià)在1.5中更正這個(gè)錯誤,而不是一個(gè)bug(真的要修復(fù)這個(gè)bug的話只要把上面這個(gè)方法刪掉就行了)。sun堅(jiān)持的正好就是樓主說的原則問題:只比較具有相同類型的兩個(gè)對象
放棄兼容性的代價(jià)就是有一些在1.4下面正常的代碼在1.5下面不能允許了,包括大名鼎鼎的JIRA。對此JIRA的反應(yīng)是:
JDK 1.5 has a bug that prevents JIRA from processing mail correctly. Until the issue is resolved, JIRA does not support JDK 1.5. We recommend you use JDK 1.4.x but it is possible to continue with JDK 1.5 by restarting the server with option \'-Dallow.jdk.1.5=true\'. You can find the JDK bug at http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=5103041
可是JIRA想要等“issue is resolved”那一天恐怕等不著了,這是個(gè)原則問題嘛 :)