blob: a56c46609f5ca66be0571b67e174c213d9a5f745 [file] [log] [blame]
/********************************************************************************
* Copyright (c) 2015-2019 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<?>> primitiveWrapperMap = 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);
public static boolean isPrimitiveWrapperOf(Class<?> targetClass, Class<?> primitive) {
if (!primitive.isPrimitive()) {
throw new IllegalArgumentException("First argument has to be primitive type");
}
return primitiveWrapperMap.get(primitive).get() == targetClass;
}
/**
* 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 isAssignableTo(Class<?> from, Class<?> to) {
if (to.isAssignableFrom(from)) {
return true;
}
if (from.isPrimitive()) {
return isPrimitiveWrapperOf(to, from);
}
if (to.isPrimitive()) {
return isPrimitiveWrapperOf(from, to);
}
return false;
}
}