I want to use Java reflection to convert the returned value of a method to a double, regardless of whether the actual return type is a Number or a primitive int, long, float, double, etc.
To ensure that the method is actually returning a value that I can convert to a double, I am using
List<String> numberTypes = Arrays.asList("int", "Integer", "double", "Double", "long", "Long", "float", "Float");
if (numberTypes.contains(method.getReturnType().getSimpleName())){
Double a = new Double( method.invoke(obj) );
}
But Eclipse tells me here that it wants me to case the output of invoke
to a Double
. Essentially it wants me to do this...
if (numberTypes.contains(method.getReturnType().getSimpleName())){
Double a = new Double( (Double) method.invoke(obj) );
}
But that seems to me like I could be introducing an error because if the object is actually a primitive int (for instance), then it seems to me like the cast would be incorrect. So the open questions:
1) Should I just insert the cast?
2) Is there a better way of converting the return value to a Double?
3) If the ultimate goal is to then convert the Double to a String, is there a shortcut I can take here? For instance, it might turn out that we ultimately just need to send the value as a String over the network. Is there a better way to accomplish the above if that is the ultimate goal?
Aucun commentaire:
Enregistrer un commentaire