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?
No, there is no easier way than what you already have in the question. The standard library does not provide a way to conventiently hide the suppression of the warning.
This is by design. Such casts are a real risk, and delay detection of programming errors - they turn a compiler error into a runtime exception.
Therefore, such unsafe casts should usually be confined to just a few places in each application, and are rarely a major concern. Most deserialization or mocking libraries etc. allow avoiding them in user code and hide them somewhere in their internals (if they are needed at all). If you need them frequently, I'd argue there is some flaw in your design.
As you mentioned encountering this frequently with a specific mocking library, perhaps you could ask a question over at CodeReview to see if there is a better way to write these tests.