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:com.netflix.spinnaker.halyard.config.model.v1.node.Node.java

/**
 * @param clazz the class to check against.
 * @param name is the name to match on.//from ww  w. ja v a2 s.  co  m
 * @return a NodeMatcher that matches all nodes of given clazz that also have the right name.
 */
static public NodeMatcher namedNodeAcceptor(Class clazz, String name) {
    return new NodeMatcher() {
        @Override
        public boolean matches(Node n) {
            return clazz.isAssignableFrom(n.getClass()) && n.getNodeName().equals(name);
        }

        @Override
        public String getName() {
            return "Match against [" + clazz.getSimpleName() + ":" + name + "]";
        }
    };
}

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</code> followed
 * by all of the elements <code>array2</code>. When an array is returned, it is always
 * a new array.</p>//from   w w w.jav  a  2 s .com
 *
 * <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 array1  the first array whose elements are added to the new array, may be <code>null</code>
 * @param array2  the second array whose elements are added to the new array, may be <code>null</code>
 * @return The new array, <code>null</code> if both arrays are <code>null</code>.
 *      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 Object[] addAll(Object[] array1, Object[] array2) {
    if (array1 == null) {
        return clone(array2);
    } else if (array2 == null) {
        return clone(array1);
    }
    Object[] joinedArray = (Object[]) Array.newInstance(array1.getClass().getComponentType(),
            array1.length + array2.length);
    System.arraycopy(array1, 0, joinedArray, 0, array1.length);
    try {
        System.arraycopy(array2, 0, joinedArray, array1.length, array2.length);
    } catch (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 type1 = array1.getClass().getComponentType();
        final Class type2 = array2.getClass().getComponentType();
        if (!type1.isAssignableFrom(type2)) {
            throw new IllegalArgumentException(
                    "Cannot store " + type2.getName() + " in an array of " + type1.getName());
        }
        throw ase; // No, so rethrow original
    }
    return joinedArray;
}

From source file:net.femtoparsec.jnlmin.utils.ReflectUtils.java

private static int findIIDistance(Class<?> lower, Class<?> upper) {
    if (!upper.isInterface() || !lower.isInterface()) {
        throw new IllegalArgumentException(
                String.format("Invalid input class : cannot be interfaces. upper=%s lower=%s", upper, lower));
    }/*w  w w  .j a  v  a2  s . co  m*/

    if (lower == upper) {
        return 0;
    }
    if (!upper.isAssignableFrom(lower)) {
        return -1;
    }

    int distance = -1;
    Class<?>[] interfaces = lower.getInterfaces();
    for (Class<?> anInterface : interfaces) {
        int tmp = findIIDistance(anInterface, upper);
        if (tmp >= 0) {
            tmp++;
            distance = distance < 0 ? tmp : Math.min(distance, tmp);
        }

        if (distance == 0) {
            //cannot do better
            break;
        }
    }

    return distance;
}

From source file:de.ifgi.fmt.utils.Utils.java

/**
 * /*from  w  ww .  jav a  2s.co  m*/
 * @param t
 * @param collClass
 * @param itemClass
 * @return
 */
public static boolean isParameterizedWith(Type t, Class<?> collClass, Class<?> itemClass) {
    if (t instanceof ParameterizedType) {
        ParameterizedType pt = (ParameterizedType) t;
        if (collClass.isAssignableFrom((Class<?>) pt.getRawType())) {
            Type argT = pt.getActualTypeArguments()[0];
            Class<?> tV = null;
            if (argT instanceof ParameterizedType) {
                tV = (Class<?>) ((ParameterizedType) argT).getRawType();
            } else if (argT instanceof Class) {
                tV = (Class<?>) argT;
            } else {
                return false;
            }
            return itemClass.isAssignableFrom(tV);
        }
    }
    return false;
}

From source file:com.tdclighthouse.prototype.utils.TdcUtils.java

@SuppressWarnings("unchecked")
public static <T> T getCachedCall(Call<T> call, HstRequest request, String attributeName) {
    T result;/*from ww w  . jav  a 2 s.c o m*/
    Class<T> type = call.getType();
    HstRequestContext requestContext = request.getRequestContext();
    if (type == null) {
        throw new IllegalArgumentException("Call Type is required.");
    }
    if (StringUtils.isBlank(attributeName)) {
        throw new IllegalArgumentException("attributeName is required.");

    }
    Object attribute = requestContext.getAttribute(attributeName);
    if (attribute != null && type.isAssignableFrom(attribute.getClass())) {
        result = (T) attribute;
    } else {
        result = call.makeCall(request);
        requestContext.setAttribute(attributeName, result);
    }

    return result;
}

From source file:Main.java

/**
 * search the method and return the defined method.
 * it will {@link Class#getMethod(String, Class[])}, if exception occurs,
 * it will search for all methods, and find the most fit method.
 *///w  w  w  .j ava  2s.co  m
public static Method searchMethod(Class<?> currentClass, String name, Class<?>[] parameterTypes, boolean boxed)
        throws NoSuchMethodException {
    if (currentClass == null) {
        throw new NoSuchMethodException("class == null");
    }
    try {
        return currentClass.getMethod(name, parameterTypes);
    } catch (NoSuchMethodException e) {
        Method likeMethod = null;
        for (Method method : currentClass.getMethods()) {
            if (method.getName().equals(name) && parameterTypes.length == method.getParameterTypes().length
                    && Modifier.isPublic(method.getModifiers())) {
                if (parameterTypes.length > 0) {
                    Class<?>[] types = method.getParameterTypes();
                    boolean eq = true;
                    boolean like = true;
                    for (int i = 0; i < parameterTypes.length; i++) {
                        Class<?> type = types[i];
                        Class<?> parameterType = parameterTypes[i];
                        if (type != null && parameterType != null && !type.equals(parameterType)) {
                            eq = false;
                            if (boxed) {
                                type = getBoxedClass(type);
                                parameterType = getBoxedClass(parameterType);
                            }
                            if (!type.isAssignableFrom(parameterType)) {
                                eq = false;
                                like = false;
                                break;
                            }
                        }
                    }
                    if (!eq) {
                        if (like && (likeMethod == null || likeMethod.getParameterTypes()[0]
                                .isAssignableFrom(method.getParameterTypes()[0]))) {
                            likeMethod = method;
                        }
                        continue;
                    }
                }
                return method;
            }
        }
        if (likeMethod != null) {
            return likeMethod;
        }
        throw e;
    }
}

From source file:com.nextep.datadesigner.Designer.java

@SuppressWarnings("unchecked")
public static <T> T getService(BundleContext context, Class<T> serviceInterface) {
    final ServiceReference ref = context.getServiceReference(serviceInterface.getName());
    if (ref != null) {
        Object o = context.getService(ref);
        if (o != null && serviceInterface.isAssignableFrom(o.getClass())) {
            return (T) o;
        }//from w  ww  .j a  v a 2 s.c om
    }
    throw new ErrorException("Unable to locate requested service " + serviceInterface.getName());
}

From source file:info.magnolia.ui.vaadin.integration.jcr.DefaultPropertyUtil.java

/**
 * Create a custom Field Object based on the Type and defaultValue.
 * If the fieldType is null, the defaultValue will be returned as String or null.
 * If the defaultValue is null, null will be returned.
 *
 * @throws NumberFormatException In case of the default value could not be parsed to the desired class.
 *///from w w  w .  j  a v a 2 s . co  m
public static Object createTypedValue(Class<?> type, String defaultValue) throws NumberFormatException {
    if (StringUtils.isBlank(defaultValue)) {
        return defaultValue;
    } else if (defaultValue != null) {
        if (type.getName().equals(String.class.getName())) {
            return defaultValue;
        } else if (type.getName().equals(Long.class.getName())) {
            return Long.decode(defaultValue);
        } else if (type.isAssignableFrom(Binary.class)) {
            return null;
        } else if (type.getName().equals(Double.class.getName())) {
            return Double.valueOf(defaultValue);
        } else if (type.getName().equals(Date.class.getName())) {
            try {
                return new SimpleDateFormat(DateUtil.YYYY_MM_DD).parse(defaultValue);
            } catch (ParseException e) {
                throw new IllegalArgumentException(e);
            }
        } else if (type.getName().equals(Boolean.class.getName())) {
            return BooleanUtils.toBoolean(defaultValue);
        } else if (type.getName().equals(BigDecimal.class.getName())) {
            return BigDecimal.valueOf(Long.decode(defaultValue));
        } else if (type.isAssignableFrom(List.class)) {
            return Arrays.asList(defaultValue.split(","));
        } else {
            throw new IllegalArgumentException("Unsupported property type " + type.getName());
        }
    }
    return null;
}

From source file:com.google.gdt.eclipse.designer.uibinder.parser.UiBinderParser.java

/**
 * @return the argument value for parameter of given type.
 *//*from   w  ww  .  j  ava2s.c o m*/
private static Object getDefaultValue(Class<?> parameterType) throws Exception {
    // try INSTANCE field
    {
        Field instanceField = ReflectionUtils.getFieldByName(parameterType, "INSTANCE");
        if (instanceField != null && ReflectionUtils.isStatic(instanceField)
                && parameterType.isAssignableFrom(instanceField.getType())) {
            return instanceField.get(null);
        }
    }
    // use default value
    return ReflectionUtils.getDefaultValue(parameterType);
}

From source file:de.codesourcery.jasm16.ast.ASTUtils.java

public static <T extends ASTNode> void visitNodesByType(ASTNode root, final ISimpleASTNodeVisitor<T> visitor,
        final Class<T> clazz) {

    final ISimpleASTNodeVisitor<ASTNode> visitor2 = new ISimpleASTNodeVisitor<ASTNode>() {

        @SuppressWarnings("unchecked")
        @Override// w w w . j a  v  a2 s.c  o m
        public boolean visit(ASTNode node) {
            if (clazz.isAssignableFrom(node.getClass())) {
                return visitor.visit((T) node);
            }
            return true;
        }
    };
    visitInOrder(root, visitor2);
}