Java Object Type Case castNumber(Number num, Class clazz)

Here you can find the source of castNumber(Number num, Class clazz)

Description

Casts provided number value to desired number type.

License

Apache License

Parameter

Parameter Description
num number value to cast
clazz number class to cast number to
T desired number type

Return

number value cast to desired numeric type

Declaration

@SuppressWarnings("unchecked")
public static <T extends Number> T castNumber(Number num, Class<T> clazz) 

Method Source Code

//package com.java2s;
/*/*w  ww.j  a  va  2s. c  o  m*/
 * Copyright 2014-2017 JKOOL, LLC.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

public class Main {
    /**
     * Casts provided number value to desired number type.
     *
     * @param num
     *            number value to cast
     * @param clazz
     *            number class to cast number to
     * @param <T>
     *            desired number type
     * @return number value cast to desired numeric type
     */
    @SuppressWarnings("unchecked")
    public static <T extends Number> T castNumber(Number num, Class<T> clazz) {
        Number cNum = 0;

        if (clazz.isAssignableFrom(Long.class)) {
            cNum = num.longValue();
        } else if (clazz.isAssignableFrom(Integer.class)) {
            cNum = num.intValue();
        } else if (clazz.isAssignableFrom(Byte.class)) {
            cNum = num.byteValue();
        } else if (clazz.isAssignableFrom(Float.class)) {
            cNum = num.floatValue();
        } else if (clazz.isAssignableFrom(Double.class)) {
            cNum = num.doubleValue();
        } else if (clazz.isAssignableFrom(Short.class)) {
            cNum = num.shortValue();
        }

        return (T) cNum;
    }
}

Related

  1. castInstance(Object o, Class clazz)
  2. castInttoLong(int x)
  3. castNode(Class jsonNode, Class classz)
  4. castNonNullArray( T [] arr)
  5. castNullableParameterTo(String parameterName, T value, Class requiredType)
  6. castObject(Class clazz, Object object)
  7. castObject(Object fromObj, Class toClass)
  8. castObject(Object ob)
  9. castOrDefault(Class type, Object value, T defaultValue, boolean allowNull)