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:eu.stratosphere.api.java.typeutils.TypeExtractor.java

private static Type getParameterType(Class<?> baseClass, ArrayList<Type> typeHierarchy, Class<?> clazz,
        int pos) {
    Type t = clazz.getGenericSuperclass();

    // check if type is child of the base class
    if (!(t instanceof Class<?> && baseClass.isAssignableFrom((Class<?>) t)) && !(t instanceof ParameterizedType
            && baseClass.isAssignableFrom((Class<?>) ((ParameterizedType) t).getRawType()))) {
        throw new IllegalArgumentException("A generic function base class must be a super class.");
    }/*ww w .  j ava2s  . c  o  m*/
    if (typeHierarchy != null) {
        typeHierarchy.add(t);
    }

    Type curT = t;
    // go up the hierarchy until we reach the base class (with or without generics)
    // collect the types while moving up for a later top-down 
    while (!(curT instanceof ParameterizedType
            && ((Class<?>) ((ParameterizedType) curT).getRawType()).equals(baseClass))
            && !(curT instanceof Class<?> && ((Class<?>) curT).equals(baseClass))) {
        if (typeHierarchy != null) {
            typeHierarchy.add(curT);
        }

        // parameterized type
        if (curT instanceof ParameterizedType) {
            curT = ((Class<?>) ((ParameterizedType) curT).getRawType()).getGenericSuperclass();
        }
        // class
        else {
            curT = ((Class<?>) curT).getGenericSuperclass();
        }
    }

    // check if immediate child of base class has generics
    if (curT instanceof Class<?>) {
        throw new InvalidTypesException("Function needs to be parameterized by using generics.");
    }

    if (typeHierarchy != null) {
        typeHierarchy.add(curT);
    }

    ParameterizedType baseClassChild = (ParameterizedType) curT;

    return baseClassChild.getActualTypeArguments()[pos];
}

From source file:com.netflix.simianarmy.aws.SimpleDBRecorder.java

/**
 * Value to enum. Converts a "name|type" string back to an enum.
 *
 * @param value/*  ww w  . ja  v a2  s .co  m*/
 *            the value
 * @return the enum
 */
private static <T extends NamedType> T valueToEnum(Class<T> type, String value) {
    // parts = [enum value, enum class type]
    String[] parts = value.split("\\|", 2);
    if (parts.length < 2) {
        throw new RuntimeException("value " + value + " does not appear to be an internal enum format");
    }

    Class<?> enumClass;
    try {
        enumClass = Class.forName(parts[1]);
    } catch (ClassNotFoundException e) {
        throw new RuntimeException("class for enum value " + value + " not found");
    }
    if (!enumClass.isEnum()) {
        throw new RuntimeException("value " + value + " does not appear to be of an enum type");
    }
    if (!type.isAssignableFrom(enumClass)) {
        throw new RuntimeException("value " + value + " cannot be assigned to a variable of this type: "
                + type.getCanonicalName());
    }
    @SuppressWarnings("rawtypes")
    Class<? extends Enum> enumType = enumClass.asSubclass(Enum.class);
    @SuppressWarnings("unchecked")
    T enumValue = (T) Enum.valueOf(enumType, parts[0]);
    return enumValue;
}

From source file:it.unibo.alchemist.language.EnvironmentBuilder.java

@SuppressWarnings("unchecked")
private static Object parseAndCreate(final Class<?> clazz, final String val, final Map<String, Object> env,
        final RandomGenerator random)
        throws InstantiationException, IllegalAccessException, InvocationTargetException {
    if (clazz.isAssignableFrom(RandomGenerator.class) && val.equalsIgnoreCase("random")) {
        L.debug("Random detected! Class " + clazz.getSimpleName() + ", param: " + val);
        if (random == null) {
            L.error("Random instatiation required, but RandomGenerator not yet defined.");
        }/*from ww w  .j  a  v  a 2  s. com*/
        return random;
    }
    if (clazz.isPrimitive() || PrimitiveUtils.classIsWrapper(clazz)) {
        L.debug(val + " is a primitive or a wrapper: " + clazz);
        if ((clazz.isAssignableFrom(Boolean.TYPE) || clazz.isAssignableFrom(Boolean.class))
                && (val.equalsIgnoreCase("true") || val.equalsIgnoreCase("false"))) {
            return Boolean.parseBoolean(val);
        }
        /*
         * If Number is in clazz's hierarchy
         */
        if (PrimitiveUtils.classIsNumber(clazz)) {
            final Optional<Number> num = extractNumber(val);
            if (num.isPresent()) {
                final Optional<Number> castNum = PrimitiveUtils.castIfNeeded(clazz, num.get());
                /*
                 * If method requires Object or unsupported Number, return
                 * what was parsed.
                 */
                return castNum.orElse(num.get());
            }
        }
        if (Character.TYPE.equals(clazz) || Character.class.equals(clazz)) {
            return val.charAt(0);
        }
    }
    if (List.class.isAssignableFrom(clazz) && val.startsWith("[") && val.endsWith("]")) {
        final List<Constructor<List<?>>> l = unsafeExtractConstructors(clazz);
        @SuppressWarnings("rawtypes")
        final List list = tryToBuild(l, new ArrayList<String>(0), env, random);
        final StringTokenizer strt = new StringTokenizer(val.substring(1, val.length() - 1), ",; ");
        while (strt.hasMoreTokens()) {
            final String sub = strt.nextToken();
            final Object o = tryToParse(sub, env, random);
            if (o == null) {
                L.debug("WARNING: list elemnt skipped: " + sub);
            } else {
                list.add(o);
            }
        }
        return list;
    }
    L.debug(val + " is not a primitive: " + clazz + ". Searching it in the environment...");
    final Object o = env.get(val);
    if (o != null && clazz.isInstance(o)) {
        return o;
    }
    if (Time.class.isAssignableFrom(clazz)) {
        return new DoubleTime(Double.parseDouble(val));
    }
    if (clazz.isAssignableFrom(String.class)) {
        L.debug("String detected! Passing " + val + " back.");
        return val;
    }
    L.debug(val + " not found or class not compatible, unable to go further.");
    return null;
}

From source file:com.xhsoft.framework.common.utils.ClassUtil.java

/**
 * //from   w  w  w .  j a v  a2  s.co m
 * @param child
 * @param parent
 * @return
 * @throws ClassNotFoundException - Class
 * @author: lizj
 */
public static Class<?> getClass(String className, String parent) throws ClassNotFoundException {
    Class<?> childClass = ClassUtil.getClass(className);

    Class<?> parentClass = null;

    if (parent == null) {
        parentClass = Object.class;
    } else {
        parentClass = ClassUtil.getClass(parent);
    }

    if (!parentClass.isAssignableFrom(childClass)) {
        throw new ClassCastException(className + " class must be implement the " + parent + " interface.");
    }

    return childClass;
}

From source file:com.mongodb.hadoop.util.MapredMongoConfigUtil.java

/**
 * Fetch a class by its actual class name, rather than by a key name in the configuration properties. We still need to pass in a
 * Configuration object here, since the Configuration class maintains an internal cache of class names for performance on some hadoop
 * versions. It also ensures that the same classloader is used across all keys.
 *///  www .j a va2 s  . c om
public static <U> Class<? extends U> getClassByName(final Configuration conf, final String className,
        final Class<U> xface) {

    if (className == null) {
        return null;
    }
    try {
        Class<?> theClass = conf.getClassByName(className);
        if (theClass != null && !xface.isAssignableFrom(theClass)) {
            throw new RuntimeException(theClass + " not " + xface.getName());
        } else if (theClass != null) {
            return theClass.asSubclass(xface);
        } else {
            return null;
        }
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}

From source file:com.github.dozermapper.core.util.MappingUtils.java

public static Class<?> determineCustomConverter(FieldMap fieldMap, Cache converterByDestTypeCache,
        CustomConverterContainer customConverterContainer, Class<?> srcClass, Class<?> destClass) {
    if (customConverterContainer == null) {
        return null;
    }//from   w w  w  .  jav a2 s  .c o  m

    // This method is messy. Just trying to isolate the junk into this one method instead of spread across the mapping
    // processor until a better solution can be put into place
    // For indexed mapping, need to use the actual class at index to determine the custom converter.
    if (fieldMap != null && fieldMap.isDestFieldIndexed()) {
        if (destClass.isArray()) {
            destClass = destClass.getComponentType();
        } else if (destClass.isAssignableFrom(Collection.class) && fieldMap.getDestHintContainer() != null
                && !fieldMap.getDestHintContainer().hasMoreThanOneHint()) {
            // use hint when trying to find a custom converter
            destClass = fieldMap.getDestHintContainer().getHint();
        }
    }

    return findCustomConverter(converterByDestTypeCache, customConverterContainer, srcClass, destClass);
}

From source file:com.tmind.framework.pub.utils.MethodUtils.java

/**
 * <p>Determine whether a type can be used as a parameter in a method invocation.
 * This method handles primitive conversions correctly.</p>
 *
 * <p>In order words, it will match a <code>Boolean</code> to a <code>boolean</code>,
 * a <code>Long</code> to a <code>long</code>,
 * a <code>Float</code> to a <code>float</code>,
 * a <code>Integer</code> to a <code>int</code>,
 * and a <code>Double</code> to a <code>double</code>.
 * Now logic widening matches are allowed.
 * For example, a <code>Long</code> will not match a <code>int</code>.
 *
 * @param parameterType the type of parameter accepted by the method
 * @param parameterization the type of parameter being tested
 *
 * @return true if the assignement is compatible.
 *///from w  w  w.j  a  v a 2s  .c  o m
public static final boolean isAssignmentCompatible(Class parameterType, Class parameterization) {
    // try plain assignment
    if (parameterType.isAssignableFrom(parameterization)) {
        return true;
    }

    if (parameterType.isPrimitive()) {
        // this method does *not* do widening - you must specify exactly
        // is this the right behaviour?
        Class parameterWrapperClazz = getPrimitiveWrapper(parameterType);
        if (parameterWrapperClazz != null) {
            return parameterWrapperClazz.equals(parameterization);
        }
    }

    return false;
}

From source file:io.siddhi.doc.gen.core.utils.DocumentationUtils.java

/**
 * Generate extension meta data from the annotated data in the class
 *
 * @param namespaceList  The list of namespaces to which the new extension will be added
 * @param extensionClass Class from which meta data should be extracted from
 * @param logger         The maven plugin logger
 *///  w ww .  j a v  a 2s.c o  m
private static void addExtensionMetaDataIntoNamespaceList(List<NamespaceMetaData> namespaceList,
        Class<?> extensionClass, Log logger) {
    Extension extensionAnnotation = extensionClass.getAnnotation(Extension.class);

    if (extensionAnnotation != null) { // Discarding extension classes without annotation
        ExtensionMetaData extensionMetaData = new ExtensionMetaData();

        // Finding extension type
        String extensionType = null;
        for (Map.Entry<ExtensionType, Class<?>> entry : ExtensionType.getSuperClassMap().entrySet()) {
            Class<?> superClass = entry.getValue();
            if (superClass.isAssignableFrom(extensionClass) && superClass != extensionClass) {
                extensionType = entry.getKey().getValue();
                break;
            }
        }

        // Discarding the extension if it belongs to an unknown type
        if (extensionType == null) {
            logger.warn("Discarding extension (belonging to an unknown extension type): "
                    + extensionClass.getCanonicalName());
            return;
        }

        extensionMetaData.setName(extensionAnnotation.name());
        extensionMetaData.setDescription(extensionAnnotation.description());

        // Adding query parameters
        ParameterMetaData[] parameters = new ParameterMetaData[extensionAnnotation.parameters().length];
        for (int i = 0; i < extensionAnnotation.parameters().length; i++) {
            Parameter parameterAnnotation = extensionAnnotation.parameters()[i];

            ParameterMetaData parameter = new ParameterMetaData();
            parameter.setName(parameterAnnotation.name());
            parameter.setType(Arrays.asList(parameterAnnotation.type()));
            parameter.setDescription(parameterAnnotation.description());
            parameter.setOptional(parameterAnnotation.optional());
            parameter.setDynamic(parameterAnnotation.dynamic());
            parameter.setDefaultValue(parameterAnnotation.defaultValue());
            parameters[i] = parameter;
        }
        extensionMetaData.setParameters(Arrays.asList(parameters));

        // Adding system parameters
        SystemParameterMetaData[] systemParameters = new SystemParameterMetaData[extensionAnnotation
                .systemParameter().length];
        for (int i = 0; i < extensionAnnotation.systemParameter().length; i++) {
            SystemParameter systemParameterAnnotation = extensionAnnotation.systemParameter()[i];

            SystemParameterMetaData systemParameter = new SystemParameterMetaData();
            systemParameter.setName(systemParameterAnnotation.name());
            systemParameter.setDescription(systemParameterAnnotation.description());
            systemParameter.setDefaultValue(systemParameterAnnotation.defaultValue());
            systemParameter
                    .setPossibleParameters(Arrays.asList(systemParameterAnnotation.possibleParameters()));
            systemParameters[i] = systemParameter;
        }
        extensionMetaData.setSystemParameters(Arrays.asList(systemParameters));

        // Adding return attributes
        ReturnAttributeMetaData[] returnAttributes = new ReturnAttributeMetaData[extensionAnnotation
                .returnAttributes().length];
        for (int i = 0; i < extensionAnnotation.returnAttributes().length; i++) {
            ReturnAttribute parameterAnnotation = extensionAnnotation.returnAttributes()[i];

            ReturnAttributeMetaData returnAttribute = new ReturnAttributeMetaData();
            returnAttribute.setName(parameterAnnotation.name());
            returnAttribute.setType(Arrays.asList(parameterAnnotation.type()));
            returnAttribute.setDescription(parameterAnnotation.description());
            returnAttributes[i] = returnAttribute;
        }
        extensionMetaData.setReturnAttributes(Arrays.asList(returnAttributes));

        // Adding examples
        ExampleMetaData[] examples = new ExampleMetaData[extensionAnnotation.examples().length];
        for (int i = 0; i < extensionAnnotation.examples().length; i++) {
            Example exampleAnnotation = extensionAnnotation.examples()[i];

            ExampleMetaData exampleMetaData = new ExampleMetaData();
            exampleMetaData.setSyntax(exampleAnnotation.syntax());
            exampleMetaData.setDescription(exampleAnnotation.description());
            examples[i] = exampleMetaData;
        }
        extensionMetaData.setExamples(Arrays.asList(examples));

        // Finding the namespace
        String namespaceName = extensionAnnotation.namespace();
        if (Objects.equals(namespaceName, "")) {
            namespaceName = Constants.CORE_NAMESPACE;
        }

        // Finding the relevant namespace in the namespace list
        NamespaceMetaData namespace = null;
        for (NamespaceMetaData existingNamespace : namespaceList) {
            if (Objects.equals(existingNamespace.getName(), namespaceName)) {
                namespace = existingNamespace;
                break;
            }
        }
        // Creating namespace if it doesn't exist
        if (namespace == null) {
            namespace = new NamespaceMetaData();
            namespace.setName(namespaceName);
            namespace.setExtensionMap(new TreeMap<>());
            namespaceList.add(namespace);
        }

        // Adding to the relevant extension metadata list in the namespace
        List<ExtensionMetaData> extensionMetaDataList = namespace.getExtensionMap()
                .computeIfAbsent(extensionType, k -> new ArrayList<>());

        extensionMetaDataList.add(extensionMetaData);
    }
}

From source file:adalid.core.XS1.java

static int round(Class<?> clazz, Artifact artifact) {
    int hits = 0;
    if (clazz != null) {
        if (artifact != null) {
            if (clazz.isAssignableFrom(getNamedClass(artifact))) {
                hits++;/*  w ww  .  j ava 2  s  . c  o m*/
            }
            Artifact declaringArtifact = artifact.getDeclaringArtifact();
            if (declaringArtifact != null) {
                hits += round(clazz, declaringArtifact);
            }
        }
    }
    return hits;
}

From source file:com.xhsoft.framework.common.utils.ClassUtil.java

/**
 * /*from  www  . j ava 2s  . c  o m*/
 * @param className
 * @param parent
 * @return
 * @throws ClassNotFoundException
 * @throws InstantiationException
 * @throws IllegalAccessException - Object
 * @author: lizj
 */
public static Object getInstance(String className, Class<?> parent)
        throws ClassNotFoundException, InstantiationException, IllegalAccessException {
    Class<?> clazz = ClassUtil.getClass(className);

    if (parent == null) {
        parent = Object.class;
    }

    if (!parent.isAssignableFrom(clazz)) {
        throw new ClassCastException(
                className + " class must be implement the " + parent.getName() + " interface.");
    }

    return clazz.newInstance();
}