Here you can find the source of cast(final Number number, final Class
Parameter | Description |
---|---|
R | the desired return type. |
number | the number to convert. |
returnType | the return type. |
public static final <R extends Number> R cast(final Number number, final Class<R> returnType)
//package com.java2s; /*// www.j ava 2 s . co m * #%L * jutility-common * %% * Copyright (C) 2013 - 2014 jutility.org * %% * 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. * #L% */ public class Main { /** * Casts the number to the provided return type. * * @param <R> * the desired return type. * * @param number * the number to convert. * @param returnType * the return type. * @return the number in the return type. */ public static final <R extends Number> R cast(final Number number, final Class<R> returnType) { if ((number == null) || (returnType == null)) { return null; } if (returnType == Double.class) { final Double value = number.doubleValue(); return returnType.cast(value); } else if (returnType == Float.class) { final Float value = number.floatValue(); return returnType.cast(value); } else if (returnType == Long.class) { final Long value = number.longValue(); return returnType.cast(value); } else if (returnType == Integer.class) { final Integer value = number.intValue(); return returnType.cast(value); } else if (returnType == Short.class) { final Short value = number.shortValue(); return returnType.cast(value); } else if (returnType == Byte.class) { final Byte value = number.byteValue(); return returnType.cast(value); } throw new UnsupportedOperationException("Cannot convert number of type " + number.getClass() + " to desired return type " + returnType + "!"); } /** * Casts the value to the provided return type. * * @param <R> * the desired return type. * * @param value * the value to convert. * @param returnType * the return type. * @return the number in the return type. */ public static final <R> R cast(final Object value, final Class<R> returnType) { if ((value == null) || (returnType == null)) { return null; } if (returnType.isAssignableFrom(value.getClass())) { return returnType.cast(value); } throw new UnsupportedOperationException("Cannot convert object of type " + value.getClass() + " to desired return type " + returnType + "!"); } }