Casting MyClass<?> to MyClass<SomeType> is generally unsafe and requires annotating the code with @SuppressWarnings("unchecked") to avoid the corresponding compiler warning. However in some cases it is easy to show that the cast is actually perfectly safe. Consider e.g. a class defined as follows:
public class MyClass<T> {
private final Class<T> type;
public MyClass(Class<T> type) {
this.type = type;
}
public Class<T> getType() {
return type;
}
}
Assume that I have references Class<SomeType> c and MyClass<?> m. If c != null && m.getType() == c then the instance m points to can only have been created as MyClass<SomeType>, i.e. casting m to MyClass<SomeType> is perfectly safe in this case. Effectively the Class object acts as a "type token" that allows me to check at runtime what the generic type of an instance of MyClass is.
The question is whether there is a technique, tool or library that allows me to write my code in a type safe way without the need to suppress warnings with @SuppressWarnings("unchecked") (for the case shown above and possibly other cases where it is straightforward to prove type safety)? More precisely I'm looking for a solution that meets the following requirements:
- It guarantees type safety, i.e. casts that are unsafe would cause an error/warning at build time or at runtime when the cast is attempted.
- It doesn't require me to write a helper method for each such case.
- It doesn't avoid the cast from
MyClass<?>toMyClass<SomeType>: to some extend it is possible to interact in a type safe way with theMyClassinstance without performing that cast (and instead using theClassinstance returned bygetType()in casts), but this is not a general solution.
I'm fairly sure it's not possible to achieve that with standard language features. I think it's not possible either to write a single generic helper method (itself relying on @SuppressWarnings("unchecked")) that would achieve that for all classes with a similar structure to the one shown above, i.e. I would have to write a helper method for each such class, contradicting the second requirement.
My assumption is the solution would require some form of code generation (e.g. with an annotation processor) that would automatically generate the necessary helper methods performing the safe casts. Does anything like that exist?