Skip to content Skip to sidebar Skip to footer

Java Object Casting Doesn't Work Like I Need It To

I'm developing native Android app on Java and I faced some unexpected behavior. Look at these classes: public class Parent { protected C mCallback; public void s

Solution 1:

You cannot cast to a C, as it doesn’t exist at runtime (ie compile time only) instead, use C instead of Object in your setCallback definition

Solution 2:

This is because of something called Type Erasure. Basically after you program is compiled generic types are replaced with their Upper Bound. So for example

classChild<TextendsVehicle>

Every instance of T is just treated as if it were a Vehicle class.

So in the code:

publicvoidsetCallback(Object callback) {
    mCallback = (C)callback;
}

During run time you are pretty much saying:

publicvoidsetCallback(Object callback) {
    mCallback = (Object)callback;
}

Since you are casting callback immediately, the simple fix for your code would to just do:

publicvoidsetCallback(C callback) {
    mCallback = callback;
}

Post a Comment for "Java Object Casting Doesn't Work Like I Need It To"