I am using some code with generics in which I am unsure why there is a compile error being thrown.
public static void main(String[] args) {
System.out.print("s");
setInteger(prepareNumber("1")); // Error here! solved by casting: setInteger((Integer)prepareNumber("1"))
Integer c = prepareInteger("1");
System.out.print(c);
}
public static Integer prepareInteger(Object number) {
return prepareNumber(number).intValue();
}
private static <T extends Number> T prepareNumber(Object number) {
T returnValue = null;
// handle a blank number
if (number == null || !NumberUtils.isNumber(number.toString())) {
returnValue = null;
} else {
if (number.toString().contains(".")) {
returnValue = (T) Double.valueOf(number.toString());
} else {
returnValue = (T) Integer.valueOf(number.toString());
}
}
return returnValue;
}
private static void setInteger(Integer a){
}
Fixing this is easy by just doing a casting, but that is undesired, as the generics should detect the method needs an Integer and should provide the return value as such and not as the super type.
PS: Do not mind the parsing code, is just testing stuff.
Thanks!
The compiler is unable to infer what type
prepareNumber("1")is supposed to return in this case. You can get it to infer correctly by placing the result in a temporary variable:Or you if
parseNumberis a static method in classYourClassyou can explicitly tell the compiler what type you expect like so:Or if you are okay with changing the method signature to help the compiler: