package com.eactive.eai.rms.common.util;

public class TypeCastUtils {

	public static <T> T cast(Object origin, Class<T> castType) throws TypeCastException {

		if (origin == null) {
			throw new TypeCastException("origin Object is null");
		}

		if (castType.isInstance(origin)) {

			return (T) origin;

		} else {
			throw new TypeCastException("origin Object is not " + castType.getName() + " instance.");
		}

	}

	public static <T> T castOrElse(Object origin, Class<T> castType, T defaultVal) {

		if (origin == null) {
			return defaultVal;
		}

		if (castType.isInstance(origin)) {

			return (T) origin;

		} else {
			return defaultVal;
		}

	}

	public static class TypeCastException extends Exception {

		private static final long serialVersionUID = 1L;

		public TypeCastException() {
			super();
		}

		public TypeCastException(String message, Throwable cause, boolean enableSuppression,
				boolean writableStackTrace) {
			super(message, cause, enableSuppression, writableStackTrace);
		}

		public TypeCastException(String message, Throwable cause) {
			super(message, cause);
		}

		public TypeCastException(String message) {
			super(message);
		}

		public TypeCastException(Throwable cause) {
			super(cause);
		}

	}

}
