CodeMonkey CodeMonkey - 1 month ago 5
Java Question

java.util.ArrayList cannot be cast to an object

I have a function with following signature:

class ABC : public static List<ObjectXYZ> getObjectXYZList(Param1 param1)


I am calling the function in a way :

List<ObjectXYZ> objectXYZ = ABC.getObjectXYZList(param1);


Now, Ideally it should work as I am assigning a variable of List, the return value of a function of type List, However I am getting the following error

java.lang.ClassCastException: java.util.ArrayList cannot be cast to com.org.lib.ObjectXYZ

Can someone suggest what might be wrong here ? May be I need to do an enforced casting around the return object ?

Updated code as MCVE, hope this is more clear

java.lang.ClassCastException: java.util.ArrayList cannot be cast to com.someorg.common.ObjectXYZ

// Calling method
List<ObjectXYZ> opaqueVoList = ABC.getObjectList(response);

// Called Method
class ABC {
public static List<ObjectXYZ> getObjectList(Response response)
throws RetryException {
if (some_condition)
List<ObjectXYZ> listObj = new ArrayList<ObjectXYZ>();
//magical stuff
return listObj;
}
}
return null;
}
}

Answer

Please look into stacktrace to see exact line where the problem occurs. First line of stacktrace should point you exactly to root cause. You may update sample code with that line, or update question with relevant part of stacktrace. Somebody is just casting ObjectXYZ to ArrayList, it seems.

Also, do not return null from method that is returning list. return Collections.emptyList() instead.

RetryException - is this org.springframework.batch.retry.RetryException ? No need to declare method to throw it, it is RuntimeException.