I've been searching for an answer for this but to no avail. My question is why is it not possible to downcast with generics. I have a class called Job and extends a class called Model
Job extends Model
Now I get a collection of Jobs from a reusable code that generates a list of Models
// error: Cannot cast from List<Model> to List<Job>
List<Job> jobs = (List<Job>) jobMapper.fetchAll();
where jobMapper.fetchAll() returns a List where each model inside it is a Job object.
I assumed this would work because I can do:
EditText mUsername = (EditText) findViewById(R.id.editUserName);
which is a simple downcasting.
Upcasting is allowed in Java, however downcasting gives a compile error. The compile error can be removed by adding a cast but would anyway break at the runtime.
Downcasting is done using cast operator. To downcast an object safely, we need instanceof operator. If the real object doesn't match the type we downcast to, then ClassCastException will be thrown at runtime.
Downcasting is not allowed without an explicit type cast. The reason for this restriction is that the is-a relationship is not, in most of the cases, symmetric. A derived class could add new data members, and the class member functions that used these data members wouldn't apply to the base class.
You cant do this, because Java does not allows this. Read this. You should do the trick:
List<Job> jobs = (List<Job>) ((List<?>)jobMapper.fetchAll());
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With