简体   繁体   中英

Avoid Unchecked Casting Warnings in Parameterized Type Casting

Is it possible to avoid the unchecked warning when typecasting a parameterized type object? For example, below is the actual situation I face, var1 is of type JComboBox<RandomType> I wish to store it in a Map and then retrieve it forcing me into the following situation.

    JComboBox<RandomType> var1 = new JComboBox<RandomType>();

    Object varRaw = var1;

    JComboBox<RandomType> var2 = (JComboBox<RandomType>) varRaw;

    JComboBox<RandomType> var3;
    if (JComboBox.class.isAssignableFrom(varRaw.getClass())) {
        var3 = JComboBox.class.cast(varRaw);
    }

Both the regular cast and the conditional casting results in the same warning.

Is it even possible to avoid that warning in this situation without having to use the @SuppressWarnings annotation?

My answer is NO, there is not a better alternative (that i know). But I am not an authoritative source and seems unwieldy to prove that EVERY other alternative does not arise a 'false' warning.

I have come to a point of assuming the lesser evil of having some warnings around (yes there is @SupressWarnings unchecked but I would like to know if something noteworthy arises). For the same reason i would frown upon the javac -Xlint:unchecked non-standard option

Other sources also say it is not possible to supress unchecked warnings in all cases (particularly when dealing with libraries not fully adapted to generics). For example in this Generics tutorial the author says

Is it possible to eliminate all "unchecked" warnings? - Almost

And then she goes into some unwieldy technical explanation that overwhelm me. Therefore I don't know if what she says counts as proof of what.

I just know I can't prove unicorns don't exist. But if I don't have notice of anyone actually registering their existence, it is fair that i assume they don't. That's Falsafiability , just take this wicked technical problem instead of stupid unicorns.

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