All Downloads are FREE. Search and download functionalities are using the official Maven repository.

com.softicar.platform.common.core.utils.CastUtils Maven / Gradle / Ivy

Go to download

The SoftiCAR Platform is a lightweight, Java-based library to create interactive business web applications.

There is a newer version: 50.0.0
Show newest version
package com.softicar.platform.common.core.utils;

import java.util.Optional;

/**
 * This class contains static utility methods for type casts.
 *
 * @author Oliver Richers
 */
public class CastUtils {

	/**
	 * Casts an object to another type.
	 * 

* The target type is determined through type inference. *

* The purpose of this method is to centralize the warnings caused by * unchecked but necessary generic type casts. Use this method only if you * know what you are doing! * * @param object * the object to cast * @return the same object casted to the target type */ @SuppressWarnings("unchecked") public static T cast(Object object) { return (T) object; } /** * Attempts to cast the given object into an instance of the given class. * * @param * the target type * @param object * the object to cast (may be null) * @param targetClass * the target class to cast the object to (never null) * @return an {@link Optional} of the casted object */ public static Optional tryCast(Object object, Class targetClass) { return Optional.ofNullable(object).filter(targetClass::isInstance).map(targetClass::cast); } /** * Attempts to cast the given object into an instance of the given class. * * @param * the target type * @param object * the object to cast (may be null) * @param targetClass * the target class to cast the object to (never null) * @return the casted object or null */ public static T castOrNull(Object object, Class targetClass) { return tryCast(object, targetClass).orElse(null); } }





© 2015 - 2024 Weber Informatics LLC | Privacy Policy