简体   繁体   中英

Why this piece of code is throwing classCastException

List<Object[]> arrayList = new ArrayList<Object[]>();
for(Object[] obj: arrayList)
{
  // assuming at 0th location Timestamp value 
  Date dt = convertTimestampToDate((Timestamp)obj[0]) // Timestampvalue , '2013-09-11 00:00:0' throwing classCastException at this line
}

public static java.sql.Date convertTimestampToDate(java.sql.Timestamp timestamp) {
        if(isNull(timestamp))
            return null;
        long milliseconds = timestamp.getTime() + (timestamp.getNanos() / 1000000);
        return new java.sql.Date(milliseconds);
    }

Exception thrown is

You cannot cast java.lang.String to Timestamp Here, I am assuming obj[0] is an object type and casting it to Timestamp Any Ideas will be appreciable.

The exception is pretty self explanatory. In Java, everything is an Object (with the exception of primitives, but that's another subject). So, even though you've got an array of Object s, that doesn't mean you can arbitrarily cast those Objects to anything you want.

Date dt = convertTimestampToDate((Timestamp)obj[0])

obj[0] is clearly a String when you attempt that cast, and as such you will need to use SimpleDateFormat or similar to parse that String . You cannot cast a String to a Timestamp for the simple reason that Java doesn't (and can't) know how to do that.

You should convert the String object to Timestamp by using the Timestamp#valueOf(String s) method.

Change

Date dt = convertTimestampToDate((Timestamp)obj[0]) ;

to

Date dt = convertTimestampToDate(Timestamp.valueOf(obj[0].toString()));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM