I have a method below doing casting on a String according to the given type, assuming the String given must be correct.
private static <T> T parsePrimitive(final Class<T> primitiveType, final String primitiveValue) {
if (primitiveType.equals(int.class) || primitiveType.equals(Integer.class)) {
return primitiveType.cast(Integer.parseInt(primitiveValue));
}
/*
...
for the rest of the primitive type
...
*/
}
However, when I call parsePrimitive(int.class, "10");,
primitiveType.cast(Integer.parseInt(primitiveValue));
This causes ClassCastException, any idea for this?
p.s. In fact, when I use Object as the return type, and no casting in before return, it works fine outside the method, but this is not generic enough I think.
Thanks in advance for any help.
You are mixing up autoboxing and casting. The java compiler will generate bytecode to box and unbox your primitives to objects and vice versa, but the same does not apply to types.
In your particular case, int.class and Integer.class are not assignable from each other.
Output:
With the amount of specialized checks you would have to put in your logic I am not sure its worth trying to come up with a generic method for parsing a String into a primitive value.