/** * Converts the given {@code subject} to the given primitive target type. Special processing applies for target * type {@code boolean.class}, see {@link #toBoolean(Object)}. * * @throws EvaluationException The {@code subject} is {@code null} (and the {@code targetType} is not {@code * boolean.class}) * @throws EvaluationException The {@code subject} cannot be converted to the given {@code targetType} */ @SuppressWarnings("unchecked") public static <T> T toPrimitive(@Nullable Object subject, Class<T> targetType) throws EvaluationException { if (!targetType.isPrimitive()) throw new AssertionError(targetType); if (targetType == boolean.class) return (T) Boolean.valueOf(ExpressionEvaluator.toBoolean(subject)); if (subject == null) { throw new EvaluationException("Cannot convert 'null' to '" + targetType.getName() + "'"); } Class<?> wrapperType = ( targetType == char.class ? Character.class : targetType == byte.class ? Byte.class : targetType == short.class ? Short.class : targetType == int.class ? Integer.class : targetType == long.class ? Long.class : targetType == float.class ? Float.class : targetType == double.class ? Double.class : ExceptionUtil.<Class<?>>throwAssertionError(targetType) ); if (subject.getClass() != wrapperType) { throw new EvaluationException("Cannot convert '" + subject.getClass() + "' to '" + targetType + "'"); } return (T) subject; }