Suppressing unchecked cast warnings with Spring CastUtils
Let’s say there are classes which are types of Vehicle. For example:
public class Bike extends Vehicle {}
public class Car extends Vehicle {}
Now, when there’s a class with a method that returns a T it may look like this:
public T getVehicle(String type) {
if (Objects.equals(type, "car")) {
return carWorker.get();
}
return bikeWorker.get();
}
Note: That’s a simplified method to focus on the problem.
The IDE will show directly the error that Vehicle or Car is not of type T.

To solve this problem a cast to T could be made:
public T getVehicle(String type) {
if (Objects.equals(type, "car")) {
return (T) carWorker.get();
}
return (T) bikeWorker.get();
}
That’ll lead to Unchecked cast warnings. The compiler is not able to assure that you will really get a T from the method, so it is warning the developer.
One solution to this could be to annotate the method with @SuppressWarnings("unchecked").
There are some problems with that:
- A warning suppression above a method may suppress warnings which we’d like to know about.
- Not everyone likes warning suppressions throughout the code.
- A warning suppression may not be allowed by code checkers in CI/CD pipelines.
Using CastUtils to suppress warnings
In Spring Boot Data there’s a CastUtils class with a cast method which does the following:
@SuppressWarnings("unchecked")
public static <T> T cast(Object object) {
return (T) object;
}
It takes the instance of an Object and casts it to T. The same thing as the getVehicle method before did.
Using this, the warning in the getVehicle method disappears:
public T getVehicle(String type) {
if (Objects.equals(type, "car")) {
return CastUtils.cast(carWorker.get());
}
return CastUtils.cast(bikeWorker.get());
}
But beware: The cast method doesn’t solve the unchecked cast. It takes just care of the warning suppression.
As you can see in the code piece, cast is annotated with @SuppressWarnings("unchecked").
So, by using the CastUtils.cast method the problem still exists, but it’s hidden/moved to another layer.
This is something which one need to be aware when using it.
Anyway, sometimes such helper methods are needed when there’s no other way to let the compiler know which types are returned.
Conclusion
By using CastUtils.cast() of the Spring Boot Data package the warning suppression can be moved when there’s an unchecked cast to T.
But the problem of an unchecked cast still persists. It’s just moved to a different place.