I have following method that I use when traversing values in JSON document:
protected static <T> T getValueAs(Object untypedValue, Class<T> expectedType) {
if (expectedType.isAssignableFrom(untypedValue.getClass())) {
return (T) untypedValue;
}
throw new RuntimeException("Failed");
}
In most of the cases it works just fine, but it fails (throws exception) when called like:
getValueAs((Long) 1L, Double.class);
I know that this is due to incompatibility of Long and Double:
Double d = (Long) 1L; results in error: incompatible types: Long cannot be converted to Double.
I wonder if somehow I can make my method work even in such case - Long value gets converted into Double?
I have seen isAssignable() from Apache Commons but I think it will only make condition work pass and things will fail on casting - I have expected type Double and value is of type Long (not primitives).