Sneaky Java cast

127 views Asked by At

In Java (Android) I had some code which looked like this:

for (Tuple tuple : xRange) {
    Tuple5<Integer, Integer, Double, Double, Double> t = (Tuple5<Integer, Integer, Double, Double, Double>)tuple;
    ...
}

Which can be a pain to write. By the way, Tuple5 derives from Tuple.

So I wrote this method:

@SuppressWarnings("unchecked")
public static final <U1, U2 extends U1> U2 cast(U1 inst) {
    return (U2)inst;
}

Looks nasty, huh? But this then allowed me to rewrite the code like this:

for (Tuple tuple : xRange) {
    Tuple5<Integer, Integer, Double, Double, Double> t = cast(tuple);
    ...
}

I'm compiling on Android using the AIDE compiler. I'm thinking it may not even compile on other systems.

My question is does this work on all compilers? Is it bad code? And, if it is, then why?

Thanks

1

There are 1 answers

4
Katona On BEST ANSWER

I think it's bad because of type erasure, it's not an accident that you get a compiler warning (which you suppress).

Your method

public static final <U1, U2> U1 cast(U2 inst) {
    return (U1)inst;
}

looks somewhat like this after type erasure:

public static final Object cast(Object inst) {
    return (Object)inst;
}

so this will not be type-safe, that cast effectively does nothing. You can read more about type erasure here.