Here you can find the source of castNumber(Number num, Class
Parameter | Description |
---|---|
num | number value to cast |
clazz | number class to cast number to |
T | desired number type |
@SuppressWarnings("unchecked") public static <T extends Number> T castNumber(Number num, Class<T> clazz)
//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; } }