Example usage for org.springframework.util NumberUtils convertNumberToTargetClass

List of usage examples for org.springframework.util NumberUtils convertNumberToTargetClass

Introduction

In this page you can find the example usage for org.springframework.util NumberUtils convertNumberToTargetClass.

Prototype

@SuppressWarnings("unchecked")
public static <T extends Number> T convertNumberToTargetClass(Number number, Class<T> targetClass)
        throws IllegalArgumentException 

Source Link

Document

Convert the given number into an instance of the given target class.

Usage

From source file:com.ebay.pulsar.analytics.dao.mapper.BaseDBMapper.java

@SuppressWarnings("unchecked")
@Override//from www  .j a va  2 s.c o  m
public T mapRow(ResultSet r, int index) throws SQLException {
    try {
        T obj = (T) clazz.newInstance();
        if (obj == null) {
            return null;
        }
        try {

            BeanInfo beanInfo = Introspector.getBeanInfo(clazz);
            PropertyDescriptor[] propertyDescriptors = beanInfo.getPropertyDescriptors();
            for (PropertyDescriptor property : propertyDescriptors) {
                String key = property.getName();
                if (!key.equals("class")) {
                    Object value = null;
                    try {
                        Method setter = property.getWriteMethod();
                        value = r.getObject(key.toLowerCase());
                        if (value != null && value instanceof Number) {
                            @SuppressWarnings("rawtypes")
                            Class[] types = setter.getParameterTypes();
                            value = NumberUtils.convertNumberToTargetClass((Number) value, types[0]);
                        }
                        if (value != null) {
                            if (value.getClass().equals(BigInteger.class)) {
                                setter.invoke(obj, ((BigInteger) value).longValue());
                            } else if (value.getClass().equals(byte[].class)) {
                                setter.invoke(obj, new String((byte[]) value));
                            } else if (Blob.class.isAssignableFrom(value.getClass())) {
                                Blob bv = (Blob) value;
                                byte[] b = new byte[(int) bv.length()];
                                InputStream stream = bv.getBinaryStream();
                                stream.read(b);
                                stream.close();
                                String v = new String(b);
                                setter.invoke(obj, v);
                            } else {
                                setter.invoke(obj, value);
                            }
                        }
                    } catch (Exception e) {
                        logger.error("transBean2Map Error " + e);
                        logger.error("name[" + key + "]=" + (value == null ? "NULL" : value.toString())
                                + ", class:" + (value == null ? "NULL" : value.getClass()) + ", err:"
                                + e.getMessage());
                    }

                }

            }
        } catch (Exception e) {
            logger.error("transBean2Map Error " + e);
        }
        return obj;
    } catch (Exception e) {
        logger.error("Exception:" + e);
    }

    return null;
}

From source file:eu.supersede.dm.ga.GAPersistentDB.java

public void create(Authentication authentication, String name, Long[] gameRequirements,
        Map<String, Map<String, Double>> playersWeights, Map<String, Double> criteriaWeights,
        Long[] gameOpinionProviders, Long gameNegotiator, Long processId) {
    DatabaseUser currentUser = (DatabaseUser) authentication.getPrincipal();
    ProcessManager mgr = DMGame.get().getProcessManager(processId);
    List<Long> requirements = new ArrayList<>();
    List<Long> opinionProviders = new ArrayList<>();

    for (Long requirementId : gameRequirements) {
        requirements.add(requirementId);
    }//w  ww.  j  a  v  a 2  s. c  o  m

    for (Long userId : gameOpinionProviders) {
        opinionProviders.add(userId);
    }

    HGAGameSummary gameSummary = new HGAGameSummary();
    long currentTime = System.currentTimeMillis();
    gameSummary.setId(currentTime);
    gameSummary.setName(name);
    gameSummary.setOwner(currentUser.getUserId());

    SimpleDateFormat sdfDate = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    Date now = new Date();
    gameSummary.setDate(sdfDate.format(now));

    gameSummary.setStatus(GAGameStatus.Open.name());
    HActivity persistentActivity = mgr.createActivity(GAMethod.NAME, currentUser.getUserId());

    // temporary workaround to avoid supervisor activities to be shown in home page
    persistentActivity.setUserId(null);
    activitiesJpa.save(persistentActivity);

    gameSummary.setActivityId(persistentActivity.getId());
    HGAGameSummary persistedGameSummary = gamesJpa.save(gameSummary);
    Long gameId = persistedGameSummary.getId();

    for (String criterionId : playersWeights.keySet()) {
        Map<String, Double> playerCriteriaWeights = playersWeights.get(criterionId);

        for (String userId : playerCriteriaWeights.keySet()) {
            Double weight = NumberUtils.convertNumberToTargetClass(playerCriteriaWeights.get(userId),
                    Double.class);
            HGAPlayerWeight playerWeight = new HGAPlayerWeight(gameId, new Long(criterionId), new Long(userId),
                    weight);
            playerWeightsJpa.save(playerWeight);
        }
    }

    for (String criterionId : criteriaWeights.keySet()) {
        HGAGameCriterion criterion = new HGAGameCriterion(gameId, new Long(criterionId),
                NumberUtils.convertNumberToTargetClass(criteriaWeights.get(criterionId), Double.class));
        criteriaJpa.save(criterion);
    }

    for (Long requirementId : requirements) {
        Requirement requirement = DMGame.get().getJpa().requirements.findOne(requirementId);

        if (requirement == null) {
            continue;
        }

        HGAGameRequirement gameRequirement = new HGAGameRequirement();
        gameRequirement.setGameId(gameId);
        gameRequirement.setRequirementId(requirement.getRequirementId());
        gameRequirementsJpa.save(gameRequirement);
    }

    for (Long userId : opinionProviders) {
        HGAGameParticipation p = new HGAGameParticipation();
        p.setGameId(gameId);
        p.setUserId(userId);
        p.setRole(GARole.OpinionProvider.name());
        participationJpa.save(p);
    }

    // Save negotiator
    HGAGameParticipation gameParticipation = new HGAGameParticipation();
    gameParticipation.setGameId(gameId);
    gameParticipation.setUserId(gameNegotiator);
    gameParticipation.setRole(GARole.Negotiator.name());
    participationJpa.save(gameParticipation);

    // Save owner
    gameParticipation = new HGAGameParticipation();
    gameParticipation.setGameId(gameId);
    gameParticipation.setUserId(gameSummary.getOwner());
    gameParticipation.setRole(GARole.Supervisor.name());
    participationJpa.save(gameParticipation);

    if (processId != -1) {
        createActivities(processId, gameId);
    }
}

From source file:ch.digitalfondue.npjt.QueryType.java

@SuppressWarnings("unchecked")
private static <T> AffectedRowCountAndKey<T> executeUpdateAndKeepKeys(String template, Method method,
        NamedParameterJdbcTemplate jdbc, SqlParameterSource parameters) {

    Class<T> keyClass = (Class<T>) ((ParameterizedType) method.getGenericReturnType())
            .getActualTypeArguments()[0];

    KeyHolder keyHolder = new GeneratedKeyHolder();

    int result = jdbc.update(template, parameters, keyHolder);
    Map<String, Object> keys = keyHolder.getKeys();
    Object key;// www .  j a  va2 s . c  o m
    if (keys.size() > 1) {
        AutoGeneratedKey spec = Objects.requireNonNull(method.getDeclaredAnnotation(AutoGeneratedKey.class),
                "more than one key for query " + template + ": annotation @AutoGeneratedKey required");
        key = Objects.requireNonNull(keys.get(spec.value()), "the key with name " + spec.value()
                + " has returned null for query " + template + ": required a non null key");
    } else if (Number.class.isAssignableFrom(keyClass)) {
        Class<? extends Number> c = (Class<? extends Number>) keyClass;
        return new AffectedRowCountAndKey<>(result,
                (T) NumberUtils.convertNumberToTargetClass(keyHolder.getKey(), c));
    } else {
        key = keys.values().iterator().next();
    }
    return new AffectedRowCountAndKey<>(result, keyClass.cast(key));
}

From source file:com.bstek.dorado.data.method.MethodAutoMatchingUtils.java

/**
 * ???//  ww w. j  a  v a2  s.  c  om
 * 
 * @param methodDescriptor
 *            ??
 * @param object
 *            ??
 * @param parameters
 *            ??
 * @return ?
 * @throws Exception
 */
@SuppressWarnings("unchecked")
private static Object invokeMethod(MethodDescriptor methodDescriptor, Object object, Object[] parameters)
        throws Exception {
    Method method = methodDescriptor.getMethod();
    Class<?>[] parameterTypes = method.getParameterTypes();
    int[] argIndexs = methodDescriptor.getArgIndexs();
    Object[] realArgs = new Object[argIndexs.length];
    for (int i = 0; i < argIndexs.length; i++) {
        Object arg = parameters[argIndexs[i]];
        if (arg != null) {
            Class<?> defType = parameterTypes[i];
            Class<?> argType = ProxyBeanUtils.getProxyTargetType(arg.getClass());
            if (!defType.isAssignableFrom(argType)) {
                if (Number.class.isAssignableFrom(defType) && Number.class.isAssignableFrom(argType)) {
                    arg = NumberUtils.convertNumberToTargetClass((Number) arg,
                            (Class<? extends Number>) defType);
                } else if (isSimpleType(defType) || isSimpleType(argType)) {
                    arg = ConvertUtils.convert(arg, defType);
                }
            }
        }
        realArgs[i] = arg;
    }
    return method.invoke(object, realArgs);
}

From source file:com.navercorp.pinpoint.collector.cluster.PinpointServerClusterPoint.java

public PinpointServerClusterPoint(PinpointServer pinpointServer) {
    AssertUtils.assertNotNull(pinpointServer, "pinpointServer may not be null.");
    this.pinpointServer = pinpointServer;

    Map<Object, Object> properties = pinpointServer.getChannelProperties();
    this.version = MapUtils.getString(properties, HandshakePropertyType.VERSION.getName());
    AssertUtils.assertTrue(!StringUtils.isBlank(version), "Version may not be null or empty.");

    this.supportCommandList = new ArrayList<>();
    Object supportCommandCodeList = properties.get(HandshakePropertyType.SUPPORT_COMMAND_LIST.getName());
    if (supportCommandCodeList instanceof List) {
        for (Object supportCommandCode : (List) supportCommandCodeList) {
            if (supportCommandCode instanceof Number) {
                TCommandType commandType = TCommandType.getType(
                        NumberUtils.convertNumberToTargetClass((Number) supportCommandCode, Short.class));
                if (commandType != null) {
                    supportCommandList.add(commandType);
                }/* www .  jav a  2 s .  c o m*/
            }
        }
    }

    this.applicationName = MapUtils.getString(properties, HandshakePropertyType.APPLICATION_NAME.getName());
    AssertUtils.assertTrue(!StringUtils.isBlank(applicationName), "ApplicationName may not be null or empty.");

    this.agentId = MapUtils.getString(properties, HandshakePropertyType.AGENT_ID.getName());
    AssertUtils.assertTrue(!StringUtils.isBlank(agentId), "AgentId may not be null or empty.");

    this.startTimeStamp = MapUtils.getLong(properties, HandshakePropertyType.START_TIMESTAMP.getName());
    AssertUtils.assertTrue(startTimeStamp > 0, "StartTimeStamp is must greater than zero.");
}

From source file:org.springframework.beans.TypeConverterDelegate.java

/**
 * Convert the value to the required type (if necessary from a String),
 * for the specified property./*from  w  w w  .ja va 2  s  . c om*/
 * @param propertyName name of the property
 * @param oldValue the previous value, if available (may be {@code null})
 * @param newValue the proposed new value
 * @param requiredType the type we must convert to
 * (or {@code null} if not known, for example in case of a collection element)
 * @param typeDescriptor the descriptor for the target property or field
 * @return the new value, possibly the result of type conversion
 * @throws IllegalArgumentException if type conversion failed
 */
@SuppressWarnings("unchecked")
@Nullable
public <T> T convertIfNecessary(@Nullable String propertyName, @Nullable Object oldValue,
        @Nullable Object newValue, @Nullable Class<T> requiredType, @Nullable TypeDescriptor typeDescriptor)
        throws IllegalArgumentException {

    // Custom editor for this type?
    PropertyEditor editor = this.propertyEditorRegistry.findCustomEditor(requiredType, propertyName);

    ConversionFailedException conversionAttemptEx = null;

    // No custom editor but custom ConversionService specified?
    ConversionService conversionService = this.propertyEditorRegistry.getConversionService();
    if (editor == null && conversionService != null && newValue != null && typeDescriptor != null) {
        TypeDescriptor sourceTypeDesc = TypeDescriptor.forObject(newValue);
        if (conversionService.canConvert(sourceTypeDesc, typeDescriptor)) {
            try {
                return (T) conversionService.convert(newValue, sourceTypeDesc, typeDescriptor);
            } catch (ConversionFailedException ex) {
                // fallback to default conversion logic below
                conversionAttemptEx = ex;
            }
        }
    }

    Object convertedValue = newValue;

    // Value not of required type?
    if (editor != null
            || (requiredType != null && !ClassUtils.isAssignableValue(requiredType, convertedValue))) {
        if (typeDescriptor != null && requiredType != null && Collection.class.isAssignableFrom(requiredType)
                && convertedValue instanceof String) {
            TypeDescriptor elementTypeDesc = typeDescriptor.getElementTypeDescriptor();
            if (elementTypeDesc != null) {
                Class<?> elementType = elementTypeDesc.getType();
                if (Class.class == elementType || Enum.class.isAssignableFrom(elementType)) {
                    convertedValue = StringUtils.commaDelimitedListToStringArray((String) convertedValue);
                }
            }
        }
        if (editor == null) {
            editor = findDefaultEditor(requiredType);
        }
        convertedValue = doConvertValue(oldValue, convertedValue, requiredType, editor);
    }

    boolean standardConversion = false;

    if (requiredType != null) {
        // Try to apply some standard type conversion rules if appropriate.

        if (convertedValue != null) {
            if (Object.class == requiredType) {
                return (T) convertedValue;
            } else if (requiredType.isArray()) {
                // Array required -> apply appropriate conversion of elements.
                if (convertedValue instanceof String
                        && Enum.class.isAssignableFrom(requiredType.getComponentType())) {
                    convertedValue = StringUtils.commaDelimitedListToStringArray((String) convertedValue);
                }
                return (T) convertToTypedArray(convertedValue, propertyName, requiredType.getComponentType());
            } else if (convertedValue instanceof Collection) {
                // Convert elements to target type, if determined.
                convertedValue = convertToTypedCollection((Collection<?>) convertedValue, propertyName,
                        requiredType, typeDescriptor);
                standardConversion = true;
            } else if (convertedValue instanceof Map) {
                // Convert keys and values to respective target type, if determined.
                convertedValue = convertToTypedMap((Map<?, ?>) convertedValue, propertyName, requiredType,
                        typeDescriptor);
                standardConversion = true;
            }
            if (convertedValue.getClass().isArray() && Array.getLength(convertedValue) == 1) {
                convertedValue = Array.get(convertedValue, 0);
                standardConversion = true;
            }
            if (String.class == requiredType && ClassUtils.isPrimitiveOrWrapper(convertedValue.getClass())) {
                // We can stringify any primitive value...
                return (T) convertedValue.toString();
            } else if (convertedValue instanceof String && !requiredType.isInstance(convertedValue)) {
                if (conversionAttemptEx == null && !requiredType.isInterface() && !requiredType.isEnum()) {
                    try {
                        Constructor<T> strCtor = requiredType.getConstructor(String.class);
                        return BeanUtils.instantiateClass(strCtor, convertedValue);
                    } catch (NoSuchMethodException ex) {
                        // proceed with field lookup
                        if (logger.isTraceEnabled()) {
                            logger.trace("No String constructor found on type [" + requiredType.getName() + "]",
                                    ex);
                        }
                    } catch (Exception ex) {
                        if (logger.isDebugEnabled()) {
                            logger.debug(
                                    "Construction via String failed for type [" + requiredType.getName() + "]",
                                    ex);
                        }
                    }
                }
                String trimmedValue = ((String) convertedValue).trim();
                if (requiredType.isEnum() && "".equals(trimmedValue)) {
                    // It's an empty enum identifier: reset the enum value to null.
                    return null;
                }
                convertedValue = attemptToConvertStringToEnum(requiredType, trimmedValue, convertedValue);
                standardConversion = true;
            } else if (convertedValue instanceof Number && Number.class.isAssignableFrom(requiredType)) {
                convertedValue = NumberUtils.convertNumberToTargetClass((Number) convertedValue,
                        (Class<Number>) requiredType);
                standardConversion = true;
            }
        } else {
            // convertedValue == null
            if (requiredType == Optional.class) {
                convertedValue = Optional.empty();
            }
        }

        if (!ClassUtils.isAssignableValue(requiredType, convertedValue)) {
            if (conversionAttemptEx != null) {
                // Original exception from former ConversionService call above...
                throw conversionAttemptEx;
            } else if (conversionService != null && typeDescriptor != null) {
                // ConversionService not tried before, probably custom editor found
                // but editor couldn't produce the required type...
                TypeDescriptor sourceTypeDesc = TypeDescriptor.forObject(newValue);
                if (conversionService.canConvert(sourceTypeDesc, typeDescriptor)) {
                    return (T) conversionService.convert(newValue, sourceTypeDesc, typeDescriptor);
                }
            }

            // Definitely doesn't match: throw IllegalArgumentException/IllegalStateException
            StringBuilder msg = new StringBuilder();
            msg.append("Cannot convert value of type '").append(ClassUtils.getDescriptiveType(newValue));
            msg.append("' to required type '").append(ClassUtils.getQualifiedName(requiredType)).append("'");
            if (propertyName != null) {
                msg.append(" for property '").append(propertyName).append("'");
            }
            if (editor != null) {
                msg.append(": PropertyEditor [").append(editor.getClass().getName())
                        .append("] returned inappropriate value of type '")
                        .append(ClassUtils.getDescriptiveType(convertedValue)).append("'");
                throw new IllegalArgumentException(msg.toString());
            } else {
                msg.append(": no matching editors or conversion strategy found");
                throw new IllegalStateException(msg.toString());
            }
        }
    }

    if (conversionAttemptEx != null) {
        if (editor == null && !standardConversion && requiredType != null && Object.class != requiredType) {
            throw conversionAttemptEx;
        }
        logger.debug("Original ConversionService attempt failed - ignored since "
                + "PropertyEditor based conversion eventually succeeded", conversionAttemptEx);
    }

    return (T) convertedValue;
}

From source file:org.springframework.binding.convert.converters.FormattedStringToNumber.java

/**
 * Coerces the Number object returned by NumberFormat to the desired numberClass. Subclasses may override.
 * @param number the parsed number/*w ww .ja  v a  2 s  .  c  om*/
 * @return the coersed number
 * @throws IllegalArgumentException when an overflow condition occurs during coersion
 */
protected Number convertToNumberClass(Number number, Class<? extends Number> numberClass)
        throws IllegalArgumentException {
    return NumberUtils.convertNumberToTargetClass(number, numberClass);
}

From source file:org.springframework.integration.redis.outbound.RedisCollectionPopulatingMessageHandler.java

@SuppressWarnings("unchecked")
private void handleZset(RedisZSet<Object> zset, final Message<?> message) throws Exception {
    final Object payload = message.getPayload();

    if (this.extractPayloadElements) {
        final BoundZSetOperations<String, Object> ops = (BoundZSetOperations<String, Object>) this.redisTemplate
                .boundZSetOps(zset.getKey());

        if ((payload instanceof Map<?, ?> && this.isMapValuesOfTypeNumber((Map<?, ?>) payload))) {
            final Map<Object, Number> pyloadAsMap = (Map<Object, Number>) payload;
            this.processInPipeline(new PipelineCallback() {
                public void process() {
                    for (Object key : pyloadAsMap.keySet()) {
                        Number d = pyloadAsMap.get(key);
                        ops.add(key, d == null ? determineScore(message)
                                : NumberUtils.convertNumberToTargetClass(d, Double.class));
                    }//  w  w w.j a  v  a 2  s. co m
                }
            });
        } else if (payload instanceof Collection<?>) {
            this.processInPipeline(new PipelineCallback() {
                public void process() {
                    for (Object object : ((Collection<?>) payload)) {
                        ops.add(object, determineScore(message));
                    }
                }
            });
        } else {
            this.addToZset(zset, payload, this.determineScore(message));
        }
    } else {
        this.addToZset(zset, payload, this.determineScore(message));
    }
}

From source file:org.springframework.integration.redis.outbound.RedisStoreWritingMessageHandler.java

@SuppressWarnings("unchecked")
private void writeToZset(RedisZSet<Object> zset, final Message<?> message) throws Exception {
    final Object payload = message.getPayload();
    final BoundZSetOperations<String, Object> ops = (BoundZSetOperations<String, Object>) this.redisTemplate
            .boundZSetOps(zset.getKey());
    final boolean zsetIncrementHeader = this.extractZsetIncrementHeader(message);
    if (this.extractPayloadElements) {
        if ((payload instanceof Map<?, ?> && this.verifyAllMapValuesOfTypeNumber((Map<?, ?>) payload))) {
            final Map<Object, Number> payloadAsMap = (Map<Object, Number>) payload;
            this.processInPipeline(new PipelineCallback() {
                public void process() {
                    for (Entry<Object, Number> entry : payloadAsMap.entrySet()) {
                        Number d = entry.getValue();
                        incrementOrOverwrite(ops, entry.getKey(),
                                d == null ? determineScore(message)
                                        : NumberUtils.convertNumberToTargetClass(d, Double.class),
                                zsetIncrementHeader);
                    }/*from w  w  w .  jav  a 2s . c om*/
                }
            });
        } else if (payload instanceof Collection<?>) {
            this.processInPipeline(new PipelineCallback() {
                public void process() {
                    for (Object object : ((Collection<?>) payload)) {
                        incrementOrOverwrite(ops, object, determineScore(message), zsetIncrementHeader);
                    }
                }
            });
        } else {
            this.incrementOrOverwrite(ops, payload, this.determineScore(message), zsetIncrementHeader);
        }
    } else {
        this.incrementOrOverwrite(ops, payload, this.determineScore(message), zsetIncrementHeader);
    }
}

From source file:org.springframework.jdbc.support.JdbcUtils.java

/**
 * Retrieve a JDBC column value from a ResultSet, using the specified value type.
 * <p>Uses the specifically typed ResultSet accessor methods, falling back to
 * {@link #getResultSetValue(java.sql.ResultSet, int)} for unknown types.
 * <p>Note that the returned value may not be assignable to the specified
 * required type, in case of an unknown type. Calling code needs to deal
 * with this case appropriately, e.g. throwing a corresponding exception.
 * @param rs is the ResultSet holding the data
 * @param index is the column index/*from  www.  ja v  a  2s .co  m*/
 * @param requiredType the required value type (may be {@code null})
 * @return the value object (possibly not of the specified required type,
 * with further conversion steps necessary)
 * @throws SQLException if thrown by the JDBC API
 * @see #getResultSetValue(ResultSet, int)
 */
@Nullable
public static Object getResultSetValue(ResultSet rs, int index, @Nullable Class<?> requiredType)
        throws SQLException {
    if (requiredType == null) {
        return getResultSetValue(rs, index);
    }

    Object value;

    // Explicitly extract typed value, as far as possible.
    if (String.class == requiredType) {
        return rs.getString(index);
    } else if (boolean.class == requiredType || Boolean.class == requiredType) {
        value = rs.getBoolean(index);
    } else if (byte.class == requiredType || Byte.class == requiredType) {
        value = rs.getByte(index);
    } else if (short.class == requiredType || Short.class == requiredType) {
        value = rs.getShort(index);
    } else if (int.class == requiredType || Integer.class == requiredType) {
        value = rs.getInt(index);
    } else if (long.class == requiredType || Long.class == requiredType) {
        value = rs.getLong(index);
    } else if (float.class == requiredType || Float.class == requiredType) {
        value = rs.getFloat(index);
    } else if (double.class == requiredType || Double.class == requiredType || Number.class == requiredType) {
        value = rs.getDouble(index);
    } else if (BigDecimal.class == requiredType) {
        return rs.getBigDecimal(index);
    } else if (java.sql.Date.class == requiredType) {
        return rs.getDate(index);
    } else if (java.sql.Time.class == requiredType) {
        return rs.getTime(index);
    } else if (java.sql.Timestamp.class == requiredType || java.util.Date.class == requiredType) {
        return rs.getTimestamp(index);
    } else if (byte[].class == requiredType) {
        return rs.getBytes(index);
    } else if (Blob.class == requiredType) {
        return rs.getBlob(index);
    } else if (Clob.class == requiredType) {
        return rs.getClob(index);
    } else if (requiredType.isEnum()) {
        // Enums can either be represented through a String or an enum index value:
        // leave enum type conversion up to the caller (e.g. a ConversionService)
        // but make sure that we return nothing other than a String or an Integer.
        Object obj = rs.getObject(index);
        if (obj instanceof String) {
            return obj;
        } else if (obj instanceof Number) {
            // Defensively convert any Number to an Integer (as needed by our
            // ConversionService's IntegerToEnumConverterFactory) for use as index
            return NumberUtils.convertNumberToTargetClass((Number) obj, Integer.class);
        } else {
            // e.g. on Postgres: getObject returns a PGObject but we need a String
            return rs.getString(index);
        }
    }

    else {
        // Some unknown type desired -> rely on getObject.
        try {
            return rs.getObject(index, requiredType);
        } catch (AbstractMethodError err) {
            logger.debug("JDBC driver does not implement JDBC 4.1 'getObject(int, Class)' method", err);
        } catch (SQLFeatureNotSupportedException ex) {
            logger.debug("JDBC driver does not support JDBC 4.1 'getObject(int, Class)' method", ex);
        } catch (SQLException ex) {
            logger.debug("JDBC driver has limited support for JDBC 4.1 'getObject(int, Class)' method", ex);
        }

        // Corresponding SQL types for JSR-310 / Joda-Time types, left up
        // to the caller to convert them (e.g. through a ConversionService).
        String typeName = requiredType.getSimpleName();
        if ("LocalDate".equals(typeName)) {
            return rs.getDate(index);
        } else if ("LocalTime".equals(typeName)) {
            return rs.getTime(index);
        } else if ("LocalDateTime".equals(typeName)) {
            return rs.getTimestamp(index);
        }

        // Fall back to getObject without type specification, again
        // left up to the caller to convert the value if necessary.
        return getResultSetValue(rs, index);
    }

    // Perform was-null check if necessary (for results that the JDBC driver returns as primitives).
    return (rs.wasNull() ? null : value);
}