Java Reflection Assignable isClassAssignableFrom(Class formal, Class actual)

Here you can find the source of isClassAssignableFrom(Class formal, Class actual)

Description

Indicates whether the formal class is assignable from the actual class, taking into account primitive promotion and auto-boxing semantics.

License

Open Source License

Declaration

@SuppressWarnings({ "unchecked", "rawtypes" })
public static boolean isClassAssignableFrom(Class formal, Class actual) 

Method Source Code


//package com.java2s;
// This package is part of the Spiralcraft project and is licensed under

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

public class Main {
    private static final Map<Class<?>, Class<?>> primitiveEquivalentMap = new HashMap<Class<?>, Class<?>>();
    private static final Map<Class<?>, Set<?>> primitiveCompatabilityMap = new HashMap<Class<?>, Set<?>>();

    /**//from  w w w  . j a v  a2 s .co m
     * Indicates whether the formal class is assignable from the actual
     *   class, taking into account primitive promotion and auto-boxing
     *   semantics.
     */
    @SuppressWarnings({ "unchecked", "rawtypes" })
    public static boolean isClassAssignableFrom(Class formal, Class actual) {
        // Suppress generic warnings b/c we're in meta-land here

        if (formal == actual) {
            return true;
        }

        if (formal.isAssignableFrom(actual)) {
            return true;
        }

        if (formal == Object.class) {
            return true;
        }

        if (actual == Void.TYPE) {
            return true;
        }

        Class actualPrimitive = primitiveEquivalent(actual);
        if (actualPrimitive == null) {
            return false;
        }

        Class formalPrimitive = primitiveEquivalent(formal);
        if (formalPrimitive == null) {
            return false;
        }

        if (actualPrimitive == formalPrimitive) {
            return true;
        }

        Set compatibleSet = primitiveCompatabilityMap.get(actualPrimitive);
        if (compatibleSet == null) {
            return false;
        }

        return compatibleSet.contains(formalPrimitive);
    }

    /**
     * Return the primitive equivalent of the specified Class
     */
    public static Class<?> primitiveEquivalent(Class<?> clazz) {
        return clazz.isPrimitive() ? clazz : primitiveEquivalentMap.get(clazz);
    }
}

Related

  1. isAssignableFrom(Class to, Class from)
  2. isAssignableFrom(Class to, Class from)
  3. isAssignableFrom(Class toClass, Class fromClass)
  4. isAssignableValue(Class type, Object value)
  5. isAssignableValue(Class type, Object value)
  6. isCompatible(Class actualType, Class parameterType)
  7. isCompatible(Class parameterType, Class parameterClass)
  8. isCompatible(Class fromClass, Class toClass)
  9. isCompatible(Class type0, Class type1)