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:kenh.xscript.impl.BaseElement.java

/**
 * Check {@code Include} annotation, if child element's class is in include
 * list, this child element is allowed to add.
 * If {@code Include} annotation do not define, all child element is allowed.
 * //from   www . jav a2s  .  c  o  m
 * @param c
 * @return true  this child element is allowed to add.
 */
private static boolean isIncludeChildElement(Element el, Class c) {
    if (!isElement(c))
        return false; // if not an Element

    Include e = el.getClass().getAnnotation(Include.class);
    if (e == null)
        return true;

    Class[] classes = e.value();
    if (classes == null || classes.length <= 0)
        return true;

    int[] numbers = e.number();
    int i = 0;
    for (Class class_ : classes) {
        int number = 0;
        if (i < numbers.length)
            number = numbers[i];
        i++;
        if (class_.isAssignableFrom(c))
            return checkChildrenElementAmount(el, number, class_);
    }

    return false;
}

From source file:org.springsource.ide.eclipse.commons.core.SpringCoreUtils.java

/**
 * Returns the specified adapter for the given object or <code>null</code>
 * if adapter is not supported.// w  w w. j a v  a 2  s  . com
 */
@SuppressWarnings("unchecked")
public static <T> T getAdapter(Object object, Class<T> adapter) {
    if (object != null && adapter != null) {
        if (adapter.isAssignableFrom(object.getClass())) {
            return (T) object;
        }
        if (object instanceof IAdaptable) {
            return (T) ((IAdaptable) object).getAdapter(adapter);
        }
    }
    return null;
}

From source file:eu.esdihumboldt.hale.common.core.io.HaleIO.java

/**
 * Get the I/O provider factories of a certain type
 * // w ww .j  a  va2  s  .co  m
 * @param providerType the provider type, usually an interface
 * @return the factories currently registered in the system
 */
public static <P extends IOProvider> Collection<IOProviderDescriptor> getProviderFactories(
        final Class<P> providerType) {
    return IOProviderExtension.getInstance()
            .getFactories(new FactoryFilter<IOProvider, IOProviderDescriptor>() {

                @Override
                public boolean acceptFactory(IOProviderDescriptor descriptor) {
                    return providerType.isAssignableFrom(descriptor.getProviderType());
                }

                @Override
                public boolean acceptCollection(
                        ExtensionObjectFactoryCollection<IOProvider, IOProviderDescriptor> collection) {
                    return true;
                }
            });
}

From source file:org.apache.hadoop.fs.s3a.TestS3AConfiguration.java

/**
 * Reads and returns a field from an object using reflection.  If the field
 * cannot be found, is null, or is not the expected type, then this method
 * fails the test./*from   ww  w.  j av  a 2s  .  c om*/
 *
 * @param target object to read
 * @param fieldType type of field to read, which will also be the return type
 * @param fieldName name of field to read
 * @return field that was read
 * @throws IllegalAccessException if access not allowed
 */
private static <T> T getField(Object target, Class<T> fieldType, String fieldName)
        throws IllegalAccessException {
    Object obj = FieldUtils.readField(target, fieldName, true);
    assertNotNull(String.format("Could not read field named %s in object with class %s.", fieldName,
            target.getClass().getName()), obj);
    assertTrue(String.format("Unexpected type found for field named %s, expected %s, actual %s.", fieldName,
            fieldType.getName(), obj.getClass().getName()), fieldType.isAssignableFrom(obj.getClass()));
    return fieldType.cast(obj);
}

From source file:com.hurence.logisland.connect.opc.CommonUtils.java

/**
 * Convert a java object to a {@link SchemaAndValue} data.
 *
 * @param value/*  ww w  . j ava2  s .  c  om*/
 * @return
 */
public static SchemaAndValue convertToNativeType(final Object value) {

    Class<?> cls = value != null ? value.getClass() : Void.class;
    final ArrayList<Object> objs = new ArrayList<>();

    if (cls.isArray()) {
        final Object[] array = (Object[]) value;

        Schema arraySchema = null;

        for (final Object element : array) {
            SchemaAndValue tmp = convertToNativeType(element);
            if (arraySchema == null) {
                arraySchema = tmp.schema();
            }
            objs.add(tmp.value());
        }

        return new SchemaAndValue(SchemaBuilder.array(arraySchema), objs);
    }

    if (cls.isAssignableFrom(Void.class)) {
        return SchemaAndValue.NULL;
    } else if (cls.isAssignableFrom(String.class)) {
        return new SchemaAndValue(SchemaBuilder.string().optional(), value);
    } else if (cls.isAssignableFrom(Short.class)) {
        return new SchemaAndValue(SchemaBuilder.int16().optional(), value);
    } else if (cls.isAssignableFrom(Integer.class)) {

        return new SchemaAndValue(SchemaBuilder.int32().optional(), value);
    } else if (cls.isAssignableFrom(Long.class)) {

        return new SchemaAndValue(SchemaBuilder.int64().optional(), value);
    } else if (cls.isAssignableFrom(Byte.class)) {
        return new SchemaAndValue(SchemaBuilder.int8().optional(), value);
    } else if (cls.isAssignableFrom(Character.class)) {
        return new SchemaAndValue(SchemaBuilder.int32().optional(),
                value == null ? null : new Integer(((char) value)));
    } else if (cls.isAssignableFrom(Boolean.class)) {
        return new SchemaAndValue(SchemaBuilder.bool().optional(), value);
    } else if (cls.isAssignableFrom(Float.class)) {
        return new SchemaAndValue(SchemaBuilder.float32().optional(), value);
    } else if (cls.isAssignableFrom(BigDecimal.class)) {
        return new SchemaAndValue(SchemaBuilder.float64().optional(),
                value == null ? null : ((BigDecimal) value).doubleValue());
    } else if (cls.isAssignableFrom(Double.class)) {
        return new SchemaAndValue(SchemaBuilder.float64().optional(), value);
    } else if (cls.isAssignableFrom(Instant.class)) {
        return new SchemaAndValue(SchemaBuilder.int64().optional(),
                value == null ? null : ((Instant) value).toEpochMilli());

    }
    throw new SchemaBuilderException("Unknown type presented (" + cls + ")");

}

From source file:kenh.xscript.impl.BaseElement.java

/**
 * Check amount of child element with certain class type.
 * // w w w  .ja  v  a2 s.  c o  m
 * @see kenh.xscript.annotation.Include#number()
 * @param number 
 * @param c
 * @return  true, this amount is less than {@code number}; false, this amount is more than {@code number}
 */
private static boolean checkChildrenElementAmount(Element el, int number, Class c) {
    if (number <= 0)
        return true;

    int i = number;
    Vector<Element> children = el.getChildren();
    for (Element child : children) {
        if (c.isAssignableFrom(child.getClass()))
            i--;
    }

    if (i <= 0)
        return false;

    return true;
}

From source file:gr.interamerican.bo2.utils.JavaBeanUtils.java

/**
 * Copies a property from a source object to a target object given two
 * respective property descriptors.//from   www. ja  v a2s . c om
 * The target's property type has to be a super-type of the source's
 * property type. If both are sub-types of {@link Number}, we use a 
 * converter to convert the source property to a type compatible with
 * the target property. This may lead to loss of precision.
 * 
 * TODO: We could also support other conversions, e.g. Character -> String
 * 
 * @param source
 * @param target
 * @param sourcePd
 * @param targetPd
 */
public static void copyProperty(Object source, Object target, PropertyDescriptor sourcePd,
        PropertyDescriptor targetPd) {
    if (source == null || target == null || sourcePd == null || targetPd == null) {
        return;
    }
    Class<?> targetPdType = targetPd.getPropertyType();
    Class<?> sourcePdType = sourcePd.getPropertyType();

    boolean assignable = targetPdType.isAssignableFrom(sourcePdType);
    boolean differentNumberTypes = Number.class.isAssignableFrom(targetPdType)
            && Number.class.isAssignableFrom(sourcePdType) && !assignable;

    if (assignable || differentNumberTypes) {
        Method getter = sourcePd.getReadMethod();
        if (getter != null) {
            Object[] getterArgs = null;
            Object value = ReflectionUtils.invoke(getter, source, getterArgs);
            Method setter = targetPd.getWriteMethod();
            if (setter != null) {
                if (differentNumberTypes) {
                    @SuppressWarnings("unchecked")
                    NumberConverter converter = new NumberConverter((Class<? extends Number>) targetPdType);
                    value = converter.execute((Number) value);
                }
                Object[] setterArgs = { value };
                ReflectionUtils.invoke(setter, target, setterArgs);
            }
        }
    }
}

From source file:com.helpinput.core.Utils.java

public static boolean isFieldType(Field field, Class<?> clz) {
    if (field != null) {
        Class<?> type = field.getType();
        if (type.isAssignableFrom(clz)) {
            return true;
        }/* ww w .  ja  v a  2  s .c o m*/
    }
    return false;
}

From source file:cn.remex.core.util.ObjectUtils.java

/**
 * Check whether the given exception is compatible with the exceptions
 * declared in a throws clause./*from w w  w.  j  a  v  a 2 s.c o  m*/
 * @param ex the exception to checked
 * @param declaredExceptions the exceptions declared in the throws clause
 * @return whether the given exception is compatible
 */
public static boolean isCompatibleWithThrowsClause(final Throwable ex, final Class<?>[] declaredExceptions) {
    if (!isCheckedException(ex)) {
        return true;
    }
    if (declaredExceptions != null) {
        for (Class<?> declaredException : declaredExceptions) {
            if (declaredException.isAssignableFrom(ex.getClass())) {
                return true;
            }
        }
    }
    return false;
}

From source file:de.micromata.genome.junittools.wicket.TpsbWicketTools.java

/**
 * Internal finder.//from  ww w .ja  va2  s.  c o m
 * 
 * @param <X> the generic type
 * @param tester the tester
 * @param startComponent the start component
 * @param componentClass the component class
 * @param matcher the matcher
 * @return the list
 */
private static <X extends Component> List<X> internalFinder(WicketTester tester, MarkupContainer startComponent,
        Class<X> componentClass, final Matcher<Component> matcher) {
    final List<X> results = new LinkedList<X>();
    Page lastRenderedPage = tester.getLastRenderedPage();

    if (lastRenderedPage == null) {
        throw new IllegalStateException("You must call #goToPage before you can find components.");
    }

    if (componentClass == null) {
        componentClass = (Class<X>) Component.class;
    }
    final Class<? extends Component> searchComponent = componentClass;

    IVisitor<Component, Object> visitor = new IVisitor<Component, Object>() {
        @Override
        public void component(Component object, IVisit<Object> visit) {
            if (LOG.isDebugEnabled() == true) {
                LOG.debug("candite for wicket internalFinder: " + object.getClass().getSimpleName() + "|"
                        + object.getId() + "|" + object.getPath());
            }
            if (searchComponent.isAssignableFrom(object.getClass()) == true) {

                if (matcher.match(object) == true) {
                    if (matcher instanceof TpsbWicketMatchSelector) {
                        results.add((X) ((TpsbWicketMatchSelector) matcher).selectMatched(object));
                    } else {
                        results.add((X) object);
                    }
                }
            }
        }
    };
    if (startComponent == null) {
        lastRenderedPage.visitChildren(visitor);
    } else {
        startComponent.visitChildren(visitor);
    }
    return results;
}