Reputation: 23510
Why class cast exception from Double to double?
Used like:
Console.writeLine(Validator.TryParse("1.5", double.class));
Code:
public static <T> T TryParse(Object ConvertFrom, java.lang.Class<T> ConvertTo) {
switch(ConvertTo.getSimpleName().toLowerCase()) {
case "int":
case "integer": return ConvertTo.cast((int)Integer.parseInt((String)ConvertFrom));
case "string": return ConvertTo.cast(String.valueOf(ConvertFrom));
case "double": return ConvertTo.cast((double)Double.parseDouble((String)ConvertFrom));
case "float": return ConvertTo.cast((float)Float.parseFloat((String)ConvertFrom));
case "long": return ConvertTo.cast((long)Long.parseLong((String)ConvertFrom));
default: return null;
}
}
Upvotes: 1
Views: 510
Reputation: 31
If you still need to define the class each time you call the validator, why don't you just use the valueOf method of each class? The Object classes such as Integer and Double will be able to handle the primitives and return objects...
As it's been asked before, are you sure you need to implement this? You might want to review your design.
Upvotes: 1
Reputation: 22692
You can use Double.doubleValue()
and Integer.intValue()
.
More reading:
Except....
Your method wants to return an Object, so you can't return primitives.
Editorial:
It seems like you're trying to do something that is very unnatural and un-Java (Java is a typed language for a reason).
Upvotes: 0
Reputation: 328669
You are mixing primitives and boxed primitives. Calling TryParse("1.5", Double.class)
will work fine (and you can remove all the unnecessary primitive casts like (int)
(double)
etc).
The problem you encounter is that Class#cast
first checks Class#isInstance
and:
Double.class.isInstance(1.0);
is true but:
double.class.isInstance(Double.valueOf(1.0))
double.class.isInstance(1.0d)
are false as explained in the javadoc
If this Class object represents a primitive type, this method returns false.
Bottom line: primitive.class.cast()
will always throw an exception.
Upvotes: 1
Reputation: 12924
It should be as below, Note the Caps in Double
.
Console.writeLine(Validator.TryParse("1.5", Double.class));
Upvotes: 0