Type aliases for Java generics

If you want full type safety, I don’t think you can do better without some kind of wrapper classes. But, why not make those classes inherit/implement the original generic versions, like this:

public class FooBBQ extends Foo<Bar<Baz,Qux>> {
...
}

This eliminates the need for toGeneric() method, and it is more clear, in my opinion, that it is just a type alias. Also, generic type can be cast into FooBBQ without a compiler warning. It would be my personal preference to make Foo, Bar, Baz... interfaces, if possible, even if some code duplication would occur in implementation.

Now, without knowing concrete problem domain, it is hard to say whether you need, say FooBBQ, like in your example, or perhaps a:

public class FooBar<X, Y> extends Foo<Bar<X, Y>> {
...
}

On the other hand, have you thought about simply configuring Java compiler not to show some of the generic warnings, and simply omit the parts of generic definition? Or, use strategically placed @SuppressWarnings("unchecked")? In other words, can you make DoableImpl only “partly genericized”:

class DoableImpl implements Doable<Foo<Bar>>,Foo<Bar>> {
    Foo<Bar> doIt(Foo<Bar> foobar) { ... } 
}

and ignore the warnings for the sake of less code clutter? Again, hard to decide without a concrete example, but it is yet another thing you can try.

Leave a Comment