Java Class Type Check isAssignable(final Class target, final Class source)

Here you can find the source of isAssignable(final Class target, final Class source)

Description

Checks if target class is assignable from source class in terms of auto(un)boxing.

License

Apache License

Parameter

Parameter Description
target target class
source source class

Return

true if target is assignable from source

Declaration

public static boolean isAssignable(final Class<?> target, final Class<?> source) 

Method Source Code

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

import java.util.*;

public class Main {
    /**//ww w  .j av a2 s .c o m
     * lookup map for matching primitive types and their object wrappers.
     */
    private static final Map<Class<?>, Class<?>> PRIMITIVES_TO_WRAPPERS = new HashMap<>();

    /**
     * Checks if target class is assignable from source class in terms of
     * auto(un)boxing. if given classes are array types then recursively checks
     * if their component types are assignable from each other.
     * <p/>
     * Note: assignable means inheritance:
     * <pre>
     *   target
     *     ^
     *     |
     *   source
     * </pre>
     *
     * @param target target class
     * @param source source class
     * @return {@code true} if target is assignable from source
     */
    public static boolean isAssignable(final Class<?> target, final Class<?> source) {
        if (target == null || source == null) {
            throw new IllegalArgumentException("classes");
        }

        if (target.isArray() && source.isArray()) {
            return isAssignable(target.getComponentType(), source.getComponentType());
        }
        return tryFromPrimitive(target).isAssignableFrom(tryFromPrimitive(source));
    }

    /**
     * Returns boxed version of given primitive type (if actually it is a
     * primitive type).
     *
     * @param type type to translate
     * @return boxed primitive class or class itself if not primitive.
     */
    public static Class<?> tryFromPrimitive(final Class<?> type) {
        if (type == null || !type.isPrimitive()) {
            return type;
        }
        return primitiveToWrapper(type);
    }

    /**
     * Returns referenced wrapper for primitive type.
     *
     * @param p class suppose to be a primitive
     * @return wrapper for primitive, {@code null} if passed type is not a
     *         primitive
     */
    public static Class<?> primitiveToWrapper(final Class<?> p) {
        return PRIMITIVES_TO_WRAPPERS.get(p);
    }
}

Related

  1. isAssignableFrom(Class clazzA, Class clazzB)
  2. isBasicType(Class clazz)
  3. isClassBelowPackage(Class theClass, List packageList)
  4. isCollection(Class clazz)