Java Reflection Assignable isPromotableFrom(Class assigneeClass, Class valueClass)

Here you can find the source of isPromotableFrom(Class assigneeClass, Class valueClass)

Description

Returns true if a variable of a given class can be assigned from a variable of a given class.

License

Apache License

Parameter

Parameter Description
assigneeClass Class of the variable to which the value being assigned, for example the argument in a method call.
valueClass Class of value being assigned.

Declaration

public static boolean isPromotableFrom(Class<?> assigneeClass, Class<?> valueClass) 

Method Source Code

//package com.java2s;
//License from project: Apache License 

import java.util.HashMap;

import java.util.Map;
import java.util.Set;

public class Main {
    private static Map<Class<?>, Class<?>> boxTypes = new HashMap<Class<?>, Class<?>>();
    private static Map<Class<?>, Set<Class<?>>> promotions = new HashMap<Class<?>, Set<Class<?>>>();

    /**// www .j a  v  a  2  s. c o  m
     * Returns true if a variable of a given class can be assigned from a
     * variable of a given class. This is equivalent to the
     * {@link Class#isAssignableFrom(Class)} method, but converts primitive
     * types to their boxed versions, and will consider promotions, e.g. from
     * int to long.
     *
     * @param assigneeClass
     *            Class of the variable to which the value being assigned, for
     *            example the argument in a method call.
     * @param valueClass
     *            Class of value being assigned.
     */
    public static boolean isPromotableFrom(Class<?> assigneeClass, Class<?> valueClass) {

        assert assigneeClass != null;
        assert valueClass != null;

        if (assigneeClass.isPrimitive()) {
            Class<?> boxClass = boxTypes.get(assigneeClass);
            assert boxClass != null : "Can't find box type for " + assigneeClass.getName();
            assigneeClass = boxClass;
        }

        if (valueClass.isPrimitive()) {
            Class<?> boxClass = boxTypes.get(valueClass);
            assert boxClass != null : "Can't find box type for " + valueClass.getName();
            valueClass = boxClass;
        }

        assert assigneeClass != null;
        assert valueClass != null;

        if (assigneeClass.isAssignableFrom(valueClass)) {
            return true;
        } else if (promotions.get(valueClass) != null && promotions.get(valueClass).contains(assigneeClass)) {
            return true;
        } else {
            return false;
        }

    }
}

Related

  1. isClassAssignableFrom(Class formal, Class actual)
  2. isCompatible(Class actualType, Class parameterType)
  3. isCompatible(Class parameterType, Class parameterClass)
  4. isCompatible(Class fromClass, Class toClass)
  5. isCompatible(Class type0, Class type1)