So as we know, Java doesn't have reified generics. That means that if you do this:
Object someObject;
Transporter<Person> transporter = (Transporter<Person>) someObject;
This produces an unchecked warning because you're now at risk that some of the objects inside the collection aren't actually of type Person
, which could be nasty if someObject
came from the outside, in a public API.
But far more commonly, at least in my own experience, you are absolutely sure that the collection only contains the given type.
So you end up doing this:
Object someObject;
@SuppressWarnings("unchecked")
Transporter<Person> transporter = (Transporter<Person>) someObject;
It's possible of course to make a convenience function which does this for you. This is how it works:
@SuppressWarnings("unchecked")
public static <T> T unsafeCast(Object object) {
return (T) object;
}
And then you can do this:
Object someObject;
Transporter<Person> transporter = unsafeCast(someObject);
That's obviously much nicer to look at, but it's such an obvious fix that I figure everyone would eventually come up with it. And if I look in source code like Gradle, I find an internal convenience method for just that. I'm sure everyone else will have the same.
We're already using Guava, and it doesn't seem to have anything of the sort.
The question is, is there a library out there which solves this sort of problem, or is everyone going to end up implementing the same method in their codebase?