How to dynamic cast/ensure typesafety from collection with varying generics-Collection of common programming errors

I don’t believe you can assign a value to an ? “typed” variable. An unbounded “?” means “the original type of the variable is unknown”, which means there is no known type it’s safe to assign to it. It doesn’t mean that the actual value of the type parameter is retrieved at runtime.

The entire idea of using a generic method to do a cast doesn’t make sense in Java generics. The only way to do a cast of an unknown type object in a type-safe way is with an actual cast.

The only solution is to get rid of the cast() method, and use raw types:

public void handle()
{
    for (IView view : this.views)
    {
        view.render(new Object());
    }
}

Assuming the cast() method is only doing casting and not type conversion. If the implementing method that ends up being called is FirstView.render(One object), I believe Java will actually cast the parameter to One. (This can also cause amusing bugs where a ClassCastException is thrown on a line of code with no casts.)

If cast() can do a type conversion (in which case, “cast” is a bad name for the operation), that means that every IView must be able to accept Object, in which case it doesn’t make much sense have the parameter of render() be the generic type to begin with. The design I would use is something like the following:

interface IView {
    void renderObject(Object o);
    void render(T);
    T coerce(Object o);
}

abstract class ViewBase implements IView {
    void renderObject(Object o) {
        render(coerce(o));
    }
}

class FirstView extends ViewBase {
    // …
}

encapsulating the “cast” operation.

There is no statically typesafe way to work with a collection of objects of different types – in Java, IView and IView are types as different as String and Integer and there are no safe conversions between the two.

Originally posted 2013-11-09 21:06:37.