Checks if the Class of the given object is assignable from a reference Class. - Java java.lang

Java examples for java.lang:Assert

Description

Checks if the Class of the given object is assignable from a reference Class.

Demo Code


//package com.java2s;

public class Main {
    public static void main(String[] argv) throws Exception {
        Object value = "java2s.com";
        Class clazz = String.class;
        System.out.println(isAssignableFrom(value, clazz));
    }/*w  ww  .j  av  a  2  s.  co  m*/

    /**
     * Checks if the Class of the given object is assignable from a reference
     * Class.
     * @param value The object to check.
     * @param clazz The reference Class.
     * @return True if value, it's Class and clazz are not null and value is
     *         assignable from clazz; false otherwise.
     */
    public static boolean isAssignableFrom(Object value, Class clazz) {
        return isAssignableFrom((value != null) ? value.getClass()
                : (Class) null, clazz);
    }

    /**
     * Checks if the given Class is assignable from a reference Class.
     * @param value The Class to check.
     * @param clazz The reference Class.
     * @return True if value and clazz are not null and value is assignable from
     *         clazz; false otherwise.
     */
    @SuppressWarnings("unchecked")
    public static boolean isAssignableFrom(Class value, Class clazz) {
        return (clazz != null) && (value != null)
                && clazz.isAssignableFrom(value); // unchecked
    }
}

Related Tutorials