Wednesday, February 14, 2007

Timestamp comparision oddities

Yesterday a colleague of mine ran into a problem where code like this produced a ClassCastException:

.. av.getEndTime().compareTo(someDate);

av is a domain class in JPA with endTime like this

@Temporal(TemporalType.TIMESTAMP)
java.util.Date endTime

and someDate being a java.util.Date.

This just worked on my Mac, but failed for one colleague, while others had no problem.
Looking under the covers turned out that av.getEndTime() actually returned a java.sql.Timestamp, which in java versions between 1.5.0_00 and 1.5.0_06 (including) were suposed to throw a CCE when the argument of compareTo() is a Date. Interstingly before() and after(), which also compare, did not have this restriction.
In Java Version 1.4.x the CCE was also not present and SUN seems to have it changed back to the original behaviour in 1.5.0_07. Unfortunately the manual page was not updated, adding to the confusion.
This blog entry also talks about this problem. Sun has a list of page about incompatibilities where this problem is listed. Unfortunately, the original bug report is not accessible (to me).

Some people argue that one should write own comparators, but I think it is easier to update to a newer version of the JDK. Of course if the software gets shipped to customers, one needs to make sure the customer also has 1.5.0_07 at least.

No comments:

Post a Comment