I want to refactor some of my methods into one method for converting string values into int/float based on method argument. for this matter I have create a method like following :
private <T>Number setNumericValue(String value , T type)
{
value = value.trim();
if(isNumeric(value))
{
if (type instanceof Integer)
return Integer.parseInt(value);
if (type instanceof Float)
return Float.parseFloat(value);
}
return 0;
}
first off I want to know is my method correct?
and for calling this method how should I use it? I’ve created something like this but java give me runtime error
this.temperatureC = setNumericValue(temperatureC, Float);
the error saying : “unable to cast Float to T”
You need to return the default value of the appropriate type too:
Your original construct wasn’t typesafe, you can’t cast a primitive value to
T extends Number. Java’s primitive type wrappers also don’t support converting between different number types usingClass.cast, so you have to do this explicitly.