Example usage for java.lang Class isAssignableFrom

List of usage examples for java.lang Class isAssignableFrom

Introduction

In this page you can find the example usage for java.lang Class isAssignableFrom.

Prototype

@HotSpotIntrinsicCandidate
public native boolean isAssignableFrom(Class<?> cls);

Source Link

Document

Determines if the class or interface represented by this Class object is either the same as, or is a superclass or superinterface of, the class or interface represented by the specified Class parameter.

Usage

From source file:fr.landel.utils.commons.NumberUtils.java

private static <N extends Number> boolean isNumberType(final N number,
        final Class<? extends Number> classNumber) {
    return number != null && classNumber.isAssignableFrom(number.getClass());
}

From source file:Main.java

/**
 * <p>Adds all the elements of the given arrays into a new array.</p>
 * <p>The new array contains all of the element of {@code array1} followed
 * by all of the elements {@code array2}. When an array is returned, it is always
 * a new array.</p>//from   w w w  . j  a v a2  s  .  co m
 *
 * <pre>
 * ArrayUtils.addAll(null, null)     = null
 * ArrayUtils.addAll(array1, null)   = cloned copy of array1
 * ArrayUtils.addAll(null, array2)   = cloned copy of array2
 * ArrayUtils.addAll([], [])         = []
 * ArrayUtils.addAll([null], [null]) = [null, null]
 * ArrayUtils.addAll(["a", "b", "c"], ["1", "2", "3"]) = ["a", "b", "c", "1", "2", "3"]
 * </pre>
 *
 * @param <T> the component type of the array
 * @param array1  the first array whose elements are added to the new array, may be {@code null}
 * @param array2  the second array whose elements are added to the new array, may be {@code null}
 * @return The new array, {@code null} if both arrays are {@code null}.
 *      The type of the new array is the type of the first array,
 *      unless the first array is null, in which case the type is the same as the second array.
 * @since 2.1
 * @throws IllegalArgumentException if the array types are incompatible
 */
public static <T> T[] addAll(final T[] array1, final T... array2) {
    if (array1 == null) {
        return clone(array2);
    } else if (array2 == null) {
        return clone(array1);
    }
    final Class<?> type1 = array1.getClass().getComponentType();
    @SuppressWarnings("unchecked")
    // OK, because array is of type T
    final T[] joinedArray = (T[]) Array.newInstance(type1, array1.length + array2.length);
    System.arraycopy(array1, 0, joinedArray, 0, array1.length);
    try {
        System.arraycopy(array2, 0, joinedArray, array1.length, array2.length);
    } catch (final ArrayStoreException ase) {
        // Check if problem was due to incompatible types
        /*
         * We do this here, rather than before the copy because:
         * - it would be a wasted check most of the time
         * - safer, in case check turns out to be too strict
         */
        final Class<?> type2 = array2.getClass().getComponentType();
        if (!type1.isAssignableFrom(type2)) {
            throw new IllegalArgumentException(
                    "Cannot store " + type2.getName() + " in an array of " + type1.getName(), ase);
        }
        throw ase; // No, so rethrow original
    }
    return joinedArray;
}

From source file:com.facebook.GraphObjectWrapper.java

static <U> U coerceValueToExpectedType(Object value, Class<U> expectedType,
        ParameterizedType expectedTypeAsParameterizedType) {
    if (value == null) {
        return null;
    }/*ww w.j  a  va 2s .c o m*/

    Class<?> valueType = value.getClass();
    if (expectedType.isAssignableFrom(valueType)) {
        @SuppressWarnings("unchecked")
        U result = (U) value;
        return result;
    }

    if (expectedType.isPrimitive()) {
        // If the result is a primitive, let the runtime succeed or fail at unboxing it.
        @SuppressWarnings("unchecked")
        U result = (U) value;
        return result;
    }

    if (GraphObject.class.isAssignableFrom(expectedType)) {
        @SuppressWarnings("unchecked")
        Class<? extends GraphObject> graphObjectClass = (Class<? extends GraphObject>) expectedType;

        // We need a GraphObject, but we don't have one.
        if (JSONObject.class.isAssignableFrom(valueType)) {
            // We can wrap a JSONObject as a GraphObject.
            @SuppressWarnings("unchecked")
            U result = (U) createGraphObjectProxy(graphObjectClass, (JSONObject) value);
            return result;
        } else if (GraphObject.class.isAssignableFrom(valueType)) {
            // We can cast a GraphObject-derived class to another GraphObject-derived class.
            @SuppressWarnings("unchecked")
            U result = (U) ((GraphObject) value).cast(graphObjectClass);
            return result;
        } else {
            throw new FacebookGraphObjectException("Can't create GraphObject from " + valueType.getName());
        }
    } else if (Iterable.class.equals(expectedType) || Collection.class.equals(expectedType)
            || List.class.equals(expectedType) || GraphObjectList.class.equals(expectedType)) {
        if (expectedTypeAsParameterizedType == null) {
            throw new FacebookGraphObjectException("can't infer generic type of: " + expectedType.toString());
        }

        Type[] actualTypeArguments = expectedTypeAsParameterizedType.getActualTypeArguments();

        if (actualTypeArguments == null || actualTypeArguments.length != 1
                || !(actualTypeArguments[0] instanceof Class<?>)) {
            throw new FacebookGraphObjectException(
                    "Expect collection properties to be of a type with exactly one generic parameter.");
        }
        Class<?> collectionGenericArgument = (Class<?>) actualTypeArguments[0];

        if (JSONArray.class.isAssignableFrom(valueType)) {
            JSONArray jsonArray = (JSONArray) value;
            @SuppressWarnings("unchecked")
            U result = (U) wrapArray(jsonArray, collectionGenericArgument);
            return result;
        } else {
            throw new FacebookGraphObjectException("Can't create Collection from " + valueType.getName());
        }
    } else if (String.class.equals(expectedType)) {
        if (Number.class.isAssignableFrom(valueType)) {
            @SuppressWarnings("unchecked")
            U result = (U) String.format("%d", value);
            return result;
        }
    } else if (Date.class.equals(expectedType)) {
        if (String.class.isAssignableFrom(valueType)) {
            for (SimpleDateFormat format : dateFormats) {
                try {
                    Date date = format.parse((String) value);
                    if (date != null) {
                        @SuppressWarnings("unchecked")
                        U result = (U) date;
                        return result;
                    }
                } catch (ParseException e) {
                    // Keep going.
                }
            }
        }
    }
    throw new FacebookGraphObjectException(
            "Can't convert type" + valueType.getName() + " to " + expectedType.getName());
}

From source file:adalid.core.XS1.java

private static Field getField(String name, Class<?> type, Class<?> top) {
    if (StringUtils.isNotBlank(name)) {
        if (top.isAssignableFrom(type)) {
            for (Field field : getFields(type, top)) {
                field.setAccessible(true);
                if (name.equals(field.getName())) {
                    return field;
                }/*from   w  ww . ja v a  2  s. co  m*/
            }
        }
    }
    return null;
}

From source file:me.xiaopan.android.gohttp.requestobject.RequestParser.java

/**
 * ?typecollectionType?collectionType=List.classtype=Date.class??DateList
 *//*from  w  ww  .j av a  2  s.  c o m*/
@SuppressWarnings("rawtypes")
private static boolean isCollectionByType(Field field, Class<? extends Collection> collectionType,
        Class<?> type) {
    Class<?> fieldType = field.getType();
    if (collectionType.isAssignableFrom(fieldType)) {
        Class<?> first = (Class<?>) ((ParameterizedType) field.getGenericType()).getActualTypeArguments()[0];
        return type.isAssignableFrom(first);
    } else {
        return false;
    }
}

From source file:org.codehaus.griffon.commons.GriffonClassUtils.java

private static boolean isTypeInstanceOfPropertyType(Class type, Class propertyType) {
    return propertyType.isAssignableFrom(type) && !propertyType.equals(Object.class);
}

From source file:com.novartis.opensource.yada.util.YADAUtils.java

/**
 * Uses java reflection to determine if {@code yadaReq} contains a plugin of {@code type}
 * @param type the plugin scope//from  w w  w .  ja v  a2 s .  c  o  m
 * @param yadaReq YADA request configuration
 * @return {@code true} if the current config references a loadable plugin class
 */
private static boolean hasPlugin(String type, YADARequest yadaReq) {
    //TODO use this method to short-circuit to plugin processing
    String[] plugin = yadaReq.getPlugin();
    if (plugin == null || plugin.length == 0) {
        return false;
    }
    Class<?> pluginClass = null;
    Class<?> pluginInterface = null;
    try {
        pluginClass = plugin[0].indexOf(YADARequest.PLUGIN_PKG) > -1 ? Class.forName(plugin[0])
                : Class.forName(YADARequest.PLUGIN_PKG + "." + plugin[0]);
        pluginInterface = Class.forName(YADARequest.PLUGIN_PKG + "." + type);
    } catch (ClassNotFoundException e) {
        e.printStackTrace();
    }

    if (pluginClass != null && pluginInterface != null && pluginInterface.isAssignableFrom(pluginClass)) // this checks plugin type
    {
        return true;
    }
    return false;
}

From source file:fr.landel.utils.commons.MapUtils2.java

/**
 * Create a new {@link HashMap} from the {@code objects}. Each objects are
 * checked and only added to the map if key and value are assignable from
 * classes.//ww  w. j  a va  2 s . co m
 * 
 * <p>
 * precondition: {@code mapProvider}, {@code keyClass}, {@code keyValue} and
 * {@code objects} cannot be {@code null}
 * </p>
 * 
 * <pre>
 * Map&lt;String, String&gt; map = MapUtils2.newHashMap(TreeMap::new, String.class, String.class, "key1", "value1", "key2", "value2");
 * 
 * // equivalent
 * Map&lt;String, String&gt; map = new TreeMap&lt;&gt;();
 * map.put("key1", "value1");
 * map.put("key2", "value2");
 * </pre>
 * 
 * @param mapProvider
 *            map constructor supplier
 * @param keyClass
 *            the class of key
 * @param valueClass
 *            the class of value
 * @param objects
 *            objects pair to put in the new {@link Map}
 * @param <K>
 *            the type of map key
 * @param <V>
 *            the type of map value
 * @param <M>
 *            the type of map
 * @return the new {@link Map}
 * @throws NullPointerException
 *             if {@code mapProvider}, {@code keyClass} or
 *             {@code valueClass} are {@code null}
 * @throws IllegalArgumentException
 *             if {@code objects} is {@code null} or empty or if
 *             {@code objects} length is even
 */
@SuppressWarnings("unchecked")
public static <K, V, M extends Map<K, V>> M newMap(final Supplier<M> mapProvider, final Class<K> keyClass,
        final Class<V> valueClass, Object... objects) {
    Objects.requireNonNull(mapProvider);
    Objects.requireNonNull(keyClass);
    Objects.requireNonNull(valueClass);
    if (objects == null || objects.length % 2 != 0) {
        throw new IllegalArgumentException(ERROR_OBJECTS_ODD);
    }

    final M map = mapProvider.get();

    int j;
    for (int i = 0; i < objects.length; i += 2) {
        j = i + 1;
        if ((objects[i] == null || keyClass.isAssignableFrom(objects[i].getClass()))
                && (objects[j] == null || valueClass.isAssignableFrom(objects[j].getClass()))) {
            map.put((K) objects[i], (V) objects[j]);
        }
    }

    return map;
}

From source file:adalid.core.XS1.java

static Field getField(boolean log, String role, String name, Class<?> type, Class<?> top,
        Class<?>... validTypes) {
    String string;//  ww w.j av a 2 s  .c  o  m
    if (StringUtils.isBlank(role)) {
        string = "field role is missing or invalid";
        if (log) {
            logFieldErrorMessage(role, name, type, null, string);
        }
        return null;
    }
    if (StringUtils.isBlank(name)) {
        string = "field name is missing or invalid";
        if (log) {
            logFieldErrorMessage(role, name, type, null, string);
        }
        return null;
    }
    if (type == null) {
        string = "class is missing or invalid";
        if (log) {
            logFieldErrorMessage(role, name, type, null, string);
        }
        return null;
    }
    Field field = getField(name, type, top);
    if (field == null) {
        string = "field " + name + " not in class";
        if (log) {
            logFieldErrorMessage(role, name, type, field, string);
        }
        return null;
    }
    int modifiers = field.getModifiers();
    if (Modifier.isStatic(modifiers) || Modifier.isFinal(modifiers)) {
        string = "field " + name + " has static and/or final modifier";
        if (log) {
            logFieldErrorMessage(role, name, type, field, string);
        }
        return null;
    }
    int length = validTypes == null ? 0 : validTypes.length;
    if (length < 1) {
        return field;
    }
    Class<?> ft = getTrueType(field.getType());
    String[] strings = new String[length];
    int i = 0;
    for (Class<?> vt : validTypes) {
        if (vt.isAssignableFrom(ft)) {
            return field;
        }
        strings[i++] = vt.getSimpleName();
    }
    string = "type of " + name + " is not " + StringUtils.join(strings, " or ");
    if (log) {
        logFieldErrorMessage(role, name, type, field, string);
    }
    return null;
}

From source file:com.bstek.dorado.util.clazz.ClassUtils.java

public static Set<Class<?>> findClassTypes(String expression, Class<?> targetType)
        throws IOException, ClassNotFoundException {
    Set<Class<?>> classTypes = new HashSet<Class<?>>();
    String pathExpression = "classpath*:" + expression.replace('.', '/') + ".class";
    Resource[] resources = ResourceUtils.getResources(pathExpression);
    for (Resource resource : resources) {
        String path = resource.getPath();
        int i1 = path.lastIndexOf('/');
        String simpleClassName = path.substring((i1 < 0) ? 0 : (i1 + 1), path.length() - 6);
        int i2 = expression.lastIndexOf('.');
        String className = expression.substring(0, i2 + 1) + simpleClassName;

        Class<?> type = null;
        try {//from   w w  w.  j a  v a 2  s.  c om
            type = ClassUtils.forName(className);
        } catch (Exception e) {
            // do nothing
        }
        if (type != null && targetType.isAssignableFrom(type)) {
            classTypes.add(type);
        }
    }
    return classTypes;
}