private <T extends ValueCommand> T readNumberCommand(Class<T> clazz)
throws SerializationException {
if (!values.hasNext()) {
throw new SerializationException("Reached end of stream");
}
ValueCommand next = values.next();
if (clazz.isInstance(next)) {
return clazz.cast(next);
} else if (next instanceof LongValueCommand) {
if (!clazz.isInstance(next)) {
throw new SerializationException("Cannot assign "
+ next.getClass().getName() + " to " + clazz.getName());
}
return clazz.cast(next);
} else if (next instanceof DoubleValueCommand) {
Exception ex;
try {
Constructor<T> c = clazz.getConstructor(double.class);
return c.newInstance(((DoubleValueCommand) next).getValue().doubleValue());
} catch (SecurityException e) {
throw new SerializationException("Cannot construct ValueCommand type",
e);
} catch (NoSuchMethodException e) {
throw new SerializationException("Connot initialize a "
+ clazz.getName() + " from a DoubleValueCommand", e);
} catch (IllegalArgumentException e) {
ex = e;
} catch (InstantiationException e) {
ex = e;
} catch (IllegalAccessException e) {
ex = e;
} catch (InvocationTargetException e) {
ex = e;
}
throw new SerializationException("Cannot create ValueCommand", ex);
} else {
throw new SerializationException(
"Cannot create a numeric ValueCommand from a "
+ next.getClass().getName());
}
}