com.softicar.platform.common.core.utils.CastUtils Maven / Gradle / Ivy
Show all versions of platform-common Show documentation
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);
}
}