Here you can find the source of isAssignable(final Class> target, final Class> source)
Parameter | Description |
---|---|
target | target class |
source | source class |
public static boolean isAssignable(final Class<?> target, final Class<?> source)
//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); } }