Example usage for java.lang Class isInstance

List of usage examples for java.lang Class isInstance

Introduction

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

Prototype

@HotSpotIntrinsicCandidate
public native boolean isInstance(Object obj);

Source Link

Document

Determines if the specified Object is assignment-compatible with the object represented by this Class .

Usage

From source file:com.norconex.jef4.suite.JobSuite.java

private void accept(IJobVisitor visitor, IJob job, Class<IJob> jobClassFilter) {
    if (job == null) {
        return;/*w w  w  . j  av a  2 s  .c o m*/
    }
    if (jobClassFilter == null || jobClassFilter.isInstance(job)) {
        IJobStatus status = null;
        if (jobSuiteStatusSnapshot != null) {
            status = jobSuiteStatusSnapshot.getJobStatus(job);
        }
        visitor.visitJob(job, status);
    }
    if (job instanceof IJobGroup) {
        for (IJob childJob : ((IJobGroup) job).getJobs()) {
            accept(visitor, childJob, jobClassFilter);
        }
    }
}

From source file:com.britesnow.snow.web.RequestContext.java

public <T> T getAttributeAs(String name, Class<T> cls, T defaultValue) {
    Object value = req.getAttribute(name);
    if (value != null) {
        if (cls.isInstance(value)) {
            return (T) value;

        } else {/*from w  w w  .  ja  v a 2  s  .  c o  m*/
            // otherwise, get get the toString and try to get it with the ObjectUtil.
            return ObjectUtil.getValue(value.toString(), cls, defaultValue);
        }
    } else {
        return defaultValue;
    }
}

From source file:ddf.camel.component.catalog.framework.FrameworkProducer.java

/**
 * Makes sure that a Metacard or Metacard ID list contains objects of a particular type
 *
 * @param list {@link java.util.List} of Metacard IDs
 * @param cls {@link java.lang.Class} type that the objects inside the list should be
 * @return true if the list is not empty and has valid types inside, else false.
 *///from w  ww  . j  a  va  2s.c  o  m
private boolean validateList(List<?> list, Class<?> cls) {
    if (CollectionUtils.isEmpty(list)) {
        LOGGER.debug("No Metacard or Metacard IDs to process");
        return false;
    }

    for (final Object o : list) {
        if (!cls.isInstance(o)) {
            LOGGER.debug("Received a list of non-{} objects", cls.getName());
            return false;
        }
    }

    return true;
}

From source file:com.workday.autoparse.json.parser.JsonParserUtils.java

private static <T> void convertJsonObjectToMap(JSONObject jsonObject, Map<String, T> map, Class<T> valueClass,
        JsonObjectParser<T> parser, String key, Class<?> unknownObjectClass,
        JsonObjectParser<?> unknownObjectParser, String discriminationName, JsonObjectParserTable parserTable)
        throws IOException {

    @SuppressWarnings("unchecked")
    Iterator<String> names = jsonObject.keys();
    while (names.hasNext()) {
        T result = null;//from   w  w w .j  a v a 2 s.com
        String name = names.next();
        Object o = jsonObject.opt(name);

        if (o instanceof JSONObject) {
            result = convertJsonObject((JSONObject) o, valueClass, parser, unknownObjectClass,
                    unknownObjectParser, discriminationName, parserTable);
        } else if (valueClass.isInstance(o)) {
            result = cast(o);
        }

        if (result != null) {
            map.put(name, result);
        } else {
            throwMapException(name, key, valueClass, o);
        }
    }
}

From source file:de.julielab.jcore.utility.JCoReAnnotationTools.java

/**
 * Returns the nearest annotations of class <tt>cls</tt> to <tt>focusAnnotation</tt>, i.e. all annotations
 * overlapping <tt>focusAnnotation</tt> where between the leftest returned annotation and the next returned
 * annotation (that is, returned offsets 0 and 1, if there are multiple returned annotations) there is no other
 * annotation of type <tt>cls</tt>.
 * <p>/*w  w w.  j av  a 2  s  .c  o  m*/
 * This method has nice performance properties when it is known that the annotation looked for is near, e.g. finding
 * overlapping tokens.
 * </p>
 * 
 * @param aJCas
 * @param focusAnnotation
 * @param cls
 * @return the leftmost annotation of type <tt>cls</tt> that completely includes <tt>focusAnnotation</tt>.
 */
@SuppressWarnings("unchecked")
public static <T extends Annotation> List<T> getNearestOverlappingAnnotations(JCas aJCas,
        Annotation focusAnnotation, Class<T> cls) {
    FSIterator<Annotation> cursor = aJCas.getAnnotationIndex().iterator();

    // for debugging: print out absolutely all annotations
    // cursor.moveToFirst();
    // while (cursor.isValid()) {
    // System.out.println(cursor.get());
    // cursor.moveToNext();
    // }

    cursor.moveTo(focusAnnotation);
    if (!cursor.isValid())
        throw new IllegalArgumentException(
                "Given FocusAnnotation was not found in the JCas' annotation index: " + focusAnnotation);

    // The annotations are sorted by begin offset. So go to the first annotation with a larger begin offset compared
    // to the focusAnnotation's end offset since then there won't be any more overlapping annotations to the right.
    while (cursor.isValid() && cursor.get().getBegin() <= focusAnnotation.getEnd()) {
        cursor.moveToNext();
    }
    if (!cursor.isValid())
        cursor.moveToLast();
    else
        cursor.moveToPrevious();

    List<T> overlappingAnnotations = new ArrayList<>();
    while (cursor.isValid()) {
        Annotation currentAnnotation = cursor.get();
        if (!cls.isInstance(currentAnnotation)) {
            cursor.moveToPrevious();
            continue;
        }
        if (cursor.isValid() && currentAnnotation.getBegin() < focusAnnotation.getEnd()
                && currentAnnotation.getEnd() > focusAnnotation.getBegin()) {
            overlappingAnnotations.add((T) currentAnnotation);
            // As soon as we have an overlapping annotation of the correct type that begins at or before the begin
            // offset of the
            // focusAnnotation, we are finished.
            if (currentAnnotation.getBegin() < focusAnnotation.getBegin()) {
                Collections.reverse(overlappingAnnotations);
                return overlappingAnnotations;
            }
        }
        cursor.moveToPrevious();
    }
    // Order by ascending begin offsets.
    Collections.reverse(overlappingAnnotations);
    return overlappingAnnotations;
}

From source file:com.surevine.alfresco.presence.xmpp.XMPPPresenceServiceImpl.java

protected boolean hasCause(Throwable t, Class<?> c) {
    if (!Throwable.class.isInstance(c)) {
        return false;
    }//from   www . j a  va 2s  .  c  o m
    Throwable top = t;
    if (c.isInstance(top)) {
        return true;
    }

    while (top.getCause() != null) {
        top = top.getCause();
        if (c.isInstance(top)) {
            return true;
        }
    }
    return false;
}

From source file:com.workday.autoparse.json.parser.JsonParserUtils.java

/**
 * Parse the next value as a {@link Map}. Children will be converted to a known type. In
 * general, this method does not handle {@link Set}s as children.
 *
 * @param reader The JsonReader to use. Calls to {@link JsonReader#beginObject()} and {@link
 * JsonReader#endObject()} will be taken care of by this method.
 * @param map The Map to populate.// w  w  w.j a  v a  2 s  .co  m
 * @param valueClass The type of the Map value, corresponding to V in Map{@literal<}K,
 * V{@literal>}.
 * @param parser The parser to use, or null if this method should find an appropriate one on its
 * own.
 * @param key The key corresponding to the current value. This is used to make more useful error
 * messages.
 * @param <T> The value type of the Map, corresponding to V in Map{@literal<}K, V{@literal>}.
 */
public static <T> void parseAsMap(JsonReader reader, Map<String, T> map, Class<T> valueClass,
        JsonObjectParser<T> parser, String key) throws IOException {
    if (handleNull(reader)) {
        return;
    }

    final String discriminationName = ContextHolder.getContext().getSettings().getDiscriminationName();
    assertType(reader, key, JsonToken.BEGIN_OBJECT);
    reader.beginObject();
    while (reader.hasNext()) {
        T value;
        String name = reader.nextName();
        if (parser != null) {
            reader.beginObject();
            value = parser.parseJsonObject(null, reader, discriminationName, null);
            reader.endObject();
        } else {
            Object o = parseNextValue(reader, true);
            if (!valueClass.isInstance(o)) {
                throwMapException(name, key, valueClass, o);
            }
            value = cast(o);

        }
        map.put(name, value);
    }
    reader.endObject();
}

From source file:com.francetelecom.clara.cloud.logicalmodel.LogicalDeployment.java

/**
 * Logical services filtered by type, and deduplicated. (Read-only), and filtered to match a given name.
 * @param filteredType the class to filter logical services or null to return all services
 * @param name an optional name/label to filter against {@link com.francetelecom.clara.cloud.logicalmodel.LogicalService#getName()} or {@link com.francetelecom.clara.cloud.logicalmodel.LogicalService#getLabel()}
 * or null to not perform any of this filtering
 * @return an unmodifiable list of logical services sorted by type and label
 *//* ww w .  j  a v  a 2  s .  c  o m*/
public <E extends LogicalService> Set<E> listLogicalServices(Class<E> filteredType, String name) {
    Set<E> services = new TreeSet<E>();
    for (LogicalService service : this.logicalServices) {
        boolean includeService = false;

        if (filteredType == null || filteredType.isInstance(service)) {
            if (name == null || name.equals(service.getName()) || name.equals(service.getLabel())) {
                includeService = true;
            }
        }

        if (includeService) {
            services.add((E) service);
        }

    }

    logger.debug(services.size() + " services of type " + filteredType + "have been found");
    return services;
}

From source file:org.apache.taverna.scufl2.validation.correctness.CorrectnessVisitor.java

public <T> T findAncestral(Child<?> bean, Class<T> class1) {
    T result = null;/*from  ww  w  . java2  s  . c o m*/
    for (WorkflowBean parent = bean.getParent(); parent != null; parent = ((Child<?>) parent).getParent()) {
        if (class1.isInstance(parent))
            return class1.cast(parent);
        if (!(parent instanceof Child))
            return null;
    }
    return result;
}