blob: 1cff072af872883fb4d151d48a5e4a580dd43c21 [file] [log] [blame]
/********************************************************************************
* Copyright (c) 2015-2018 Contributors to the Eclipse Foundation
*
* See the NOTICE file(s) distributed with this work for additional
* information regarding copyright ownership.
*
* This program and the accompanying materials are made available under the
* terms of the Eclipse Public License v. 2.0 which is available at
* http://www.eclipse.org/legal/epl-2.0.
*
* SPDX-License-Identifier: EPL-2.0
*
********************************************************************************/
package org.eclipse.mdm.businessobjects.utils;
import io.vavr.collection.HashMap;
import io.vavr.collection.Map;
/**
* Utility class for method reflection
*
* @author Johannes Stamm, Peak Solution GmbH Nuernberg
*
*/
public class ReflectUtil {
private static final Map<Class<?>, Class<?>> TYPE_MAP = HashMap.of(boolean.class, Boolean.class, byte.class,
Byte.class, char.class, Character.class, double.class, Double.class, float.class, Float.class, int.class,
Integer.class, long.class, Long.class, short.class, Short.class);
/**
* This function returns same value as to.isAssignableFrom(from), except for
* wrapper classes.
*
* to.isAssignableFrom(from) returns false for wrapper class <-> primitive This
* function returns true in that case.
*
* @param from class to assign from
* @param to class to assign to
* @return true if assigning is possible (respecting auto boxing/unboxing) false
* otherwise
*/
public static boolean isAssignable(Class<?> from, Class<?> to) {
return to.isAssignableFrom(from) || isPrimitiveWrapperOf(to, from) || isPrimitiveWrapperOf(from, to);
}
/**
* Checks if wrapperClazz is wrapper class of primitiveClazz.
*
* @param wrapperClazz the wrapper class
* @param primitiveClazz the primitive class
* @return True if wrapperClazz is wrapper class of primitiveClazz, false
* otherwise.
*/
private static boolean isPrimitiveWrapperOf(Class<?> wrapperClazz, Class<?> primitiveClazz) {
return TYPE_MAP.get(primitiveClazz).map(c -> c == wrapperClazz).getOrElse(false);
}
}