Here you can find the source of castOrDefault(Class
Parameter | Description |
---|---|
type | the type to which the value should be cast |
value | the value to be cast |
defaultValue | the default value to be returned if the cast is not possible or if the value is null and null values are not allowed. |
allowNull | if false and the value is null, the defaultValue will be returned. |
T | the type to which the value should be cast and the type of the defaultValue . |
@SuppressWarnings("unchecked") public static <T> T castOrDefault(Class<T> type, Object value, T defaultValue, boolean allowNull)
//package com.java2s; /**/*from w w w . j a v a 2 s.co m*/ * Copyright 2015-2016 the original author or authors. * * 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 a value to another type, returning a default value if the cast is not possible or if the value is null and null values are not allowed. * @param type the type to which the value should be cast * @param value the value to be cast * @param defaultValue the default value to be returned if the cast is not possible or if the {@code value} is null and null values are not allowed. * @param allowNull if false and the {@code value} is null, the {@code defaultValue} will be returned. * @param <T> the type to which the value should be cast and the type of the {@code defaultValue}. * @return the result of the cast or the {@code defaultValue} if the cast is not possible or if the value is null and null values are not allowed. */ @SuppressWarnings("unchecked") public static <T> T castOrDefault(Class<T> type, Object value, T defaultValue, boolean allowNull) { if (value == null) return allowNull ? null : defaultValue; if (!type.isAssignableFrom(value.getClass())) { return defaultValue; } return (T) value; } }