I have a generic factory that returns a controller and I would like to avoid an Unchecked Cast warning without using @SuppressWarnings.
In my example below, the factory uses two different ways of returning a controller. The first one ((BallController<T>) getBaseballController();) causes an Unchecked Cast warning. The second one ((BallController<T>) someOtherClass.getFootballController();) does not cause any warnings.
public class BallControllerFactory {
public BaseballController getBaseballController() {
return new BaseballController();
}
public <T extends Ball> BallController<T> getBallController(T ball) {
if(ball instanceof Baseball) {
return (BallController<T>) getBaseballController();
}
else if(ball instanceof Football) {
SomeOtherClass someOtherClass = new SomeOtherClass();
return (BallController<T>) someOtherClass.getFootballController();
}
//No controller found
return null;
}
}
As you can see, just by moving the getXXXController method to a delegate class, the warning is eliminated. Here is the SomeOtherClass, just so you can see nothing special is happening.
public class SomeOtherClass {
public FootballController getFootballController() {
return new FootballController();
}
}
My question is, why is it that when I use a delegate method to return the controller I do not get the Unchecked Cast warning, but when I use a local method I do?
For the sake of completeness, here are the other class definitions (all are empty classes).
public class BallController<T extends Ball>
public class BaseballController extends BallController<Baseball>
public class FootballController extends BallController<Football>
public class Ball
public class Baseball extends Ball
public class Football extends Ball
Although your warning message are inconsistent for some reason (you should get warnings on both), the fix for your situation is to change:
public <T extends Ball> BallController<T> getBallController(T ball) {
to
public <T extends Ball> BallController<?> getBallController(T ball) {
and remove the casts:
return (BallController<T>) getBaseballController();
return (BallController<T>) someOtherClass.getFootballController();
like:
return getBaseballController();
return someOtherClass.getFootballController();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With