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.taobao.adfs.database.tdhsocket.client.response.TDHSResutSet.java

public boolean isWrapperFor(Class<?> iface) throws SQLException {
    return iface.isInstance(this);
}

From source file:net.fenyo.gnetwatch.GUI.VisualElement.java

/**
 * Gets sub elements of a given type.//from www  . j  a  va  2  s  .  c  om
 * @param clazz type.
 * @param elts list that will be updated.
 * @return void.
 */
private void getSubElements(final Class clazz, final java.util.List<VisualElement> elts) {
    for (final VisualElement elt : getChildren())
        elt.getSubElements(clazz, elts);
    if (clazz.isInstance(this) && !elts.contains(this))
        elts.add(this);
}

From source file:de.static_interface.sinklibrary.SinkLibrary.java

/**
 * @param base Base of the User// w w  w  .jav  a 2s.  c o  m
 * @return IUser instance of sender, e.g. if sender is {@link ConsoleCommandSender}, it will return {@link ConsoleUser}.
 *         <br/> May return null if there is no default implementation
 */
@Nullable
public SinkUser getUser(Object base) {
    if (base instanceof IrcCommandSender) {
        base = ((IrcCommandSender) base).getUser().getBase();
    }

    for (Class<?> implClass : getUserImplementations().keySet()) {
        if (implClass.isInstance(base)) {
            SinkUserProvider provider = getUserImplementations().get(implClass);

            if (provider instanceof IrcUserProvider) {
                return ((IrcUserProvider) provider).getUserInstance(((User) base).getNick());
            }

            return getUserImplementations().get(implClass).getUserInstance(base);
        }
    }

    //Todo: add default implementation for not supported bases/CommandSenders
    return null;
}

From source file:iDynoOptimizer.MOEAFramework26.src.org.moeaframework.algorithm.StandardAlgorithms.java

/**
 * Returns {@code true} if all decision variables are assignment-compatible
 * with the specified type; {@code false} otherwise.
 * /*from www . j  a v a  2  s. c  o  m*/
 * @param type the type of decision variable
 * @param problem the problem
 * @return {@code true} if all decision variables are assignment-compatible
 *         with the specified type; {@code false} otherwise
 */
private boolean checkType(Class<? extends Variable> type, Problem problem) {
    Solution solution = problem.newSolution();

    for (int i = 0; i < solution.getNumberOfVariables(); i++) {
        if (!type.isInstance(solution.getVariable(i))) {
            return false;
        }
    }

    return true;
}

From source file:edu.vt.middleware.ldap.AbstractLdap.java

/**
 * Confirms whether the supplied exception matches an exception from {@link
 * LdapConfig#getOperationRetryExceptions()} and the supplied count is less
 * than {@link LdapConfig#getOperationRetry()}. {@link
 * LdapConfig#getOperationRetryWait()} is used in conjunction with {@link
 * LdapConfig#getOperationRetryBackoff()} to delay retries. Calls {@link
 * #close()} if no exception is thrown, which allows the client to reconnect
 * when the operation is performed again.
 *
 * @param  ctx  <code>LdapContext</code> that performed the operation
 * @param  e  <code>NamingException</code> that was thrown
 * @param  count  <code>int</code> operation attempts
 *
 * @throws  NamingException  if the operation won't be retried
 *//* w ww. jav  a 2s .com*/
protected void operationRetry(final LdapContext ctx, final NamingException e, final int count)
        throws NamingException {
    boolean ignoreException = false;
    final Class<?>[] ignore = this.config.getOperationRetryExceptions();
    if (ignore != null && ignore.length > 0) {
        for (Class<?> ne : ignore) {
            if (ne.isInstance(e)) {
                ignoreException = true;
                break;
            }
        }
    }
    if (ignoreException && (count < this.config.getOperationRetry() || this.config.getOperationRetry() == -1)) {
        if (this.logger.isWarnEnabled()) {
            this.logger.warn("Error performing LDAP operation, " + "retrying (attempt " + count + ")", e);
        }
        if (ctx != null) {
            ctx.close();
        }
        this.close();
        if (this.config.getOperationRetryWait() > 0) {
            long sleepTime = this.config.getOperationRetryWait();
            if (this.config.getOperationRetryBackoff() > 0 && count > 0) {
                sleepTime = sleepTime * this.config.getOperationRetryBackoff() * count;
            }
            try {
                Thread.sleep(sleepTime);
            } catch (InterruptedException ie) {
                if (this.logger.isDebugEnabled()) {
                    this.logger.debug("Operation retry wait interrupted", e);
                }
            }
        }
    } else {
        throw e;
    }
}

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

/**
 * Returns, in ascending order, all annotations of type <tt>cls</tt> that are completely included - perhaps with
 * having the same begin and/or end as the <tt>focusAnnotation</tt> - in <tt>focusAnnotation</tt>.
 * //from   w  ww.j a v a2 s  .c  om
 * @param aJCas
 * @param focusAnnotation
 * @param cls
 * @return
 */
@SuppressWarnings("unchecked")
public static <T extends Annotation> List<T> getIncludedAnnotations(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 lower begin offset compared
    // to the focusAnnotation.
    while (cursor.isValid() && cursor.get().getBegin() >= focusAnnotation.getBegin()) {
        cursor.moveToPrevious();
    }
    if (!cursor.isValid())
        cursor.moveToFirst();
    else
        cursor.moveToNext();

    // Now that we have our starting point, we go to the right as long as there is a possibility to still find
    // annotations included in the focusAnnotation, i.e. as long the current begin offset is still lower (or equal
    // for the weird case of zero-length-annotations) than the
    // end offset of the focusAnnotation
    Annotation currentAnnotation = null;
    List<T> includedAnnotations = new ArrayList<>();
    while (cursor.isValid() && (currentAnnotation = cursor.get()).getBegin() <= focusAnnotation.getEnd()) {
        if (!cls.isInstance(currentAnnotation)) {
            cursor.moveToNext();
            continue;
        }
        Range<Integer> currentRange = Range.between(currentAnnotation.getBegin(), currentAnnotation.getEnd());
        Range<Integer> focusRange = Range.between(focusAnnotation.getBegin(), focusAnnotation.getEnd());
        if (cursor.isValid() && cls.isInstance(currentAnnotation) && focusRange.containsRange(currentRange))
            includedAnnotations.add((T) currentAnnotation);
        cursor.moveToNext();
    }
    return includedAnnotations;
}

From source file:de.sanandrew.mods.claysoldiers.entity.EntityClayMan.java

public boolean hasUpgrade(Class upgradeClass) {
    for (ASoldierUpgrade upgrade : this.p_upgrades.keySet()) {
        if (upgradeClass.isInstance(upgrade)) {
            return true;
        }// w w w  . ja  v a2s  .  c o m
    }
    return false;
}

From source file:org.opennms.netmgt.correlation.ncs.EventMappingRulesTest.java

private void testEventDup(Event event, Event event2, Class<? extends ComponentEvent> componentEventClass,
        String componentType, String componentForeignSource, String componentForeignId) {
    // Get engine
    DroolsCorrelationEngine engine = findEngineByName("eventMappingRules");

    assertEquals("Expected nothing but got " + engine.getMemoryObjects(), 0, engine.getMemorySize());

    engine.correlate(event);//  w w w . j  av a  2s .  co m

    List<Object> memObjects = engine.getMemoryObjects();

    assertEquals("Unexpected size of workingMemory " + memObjects, 1, memObjects.size());

    Object eventObj = memObjects.get(0);

    assertTrue(componentEventClass.isInstance(eventObj));
    assertTrue(eventObj instanceof ComponentEvent);

    ComponentEvent c = (ComponentEvent) eventObj;

    assertSame(event, c.getEvent());

    Component component = c.getComponent();
    assertEquals(componentType, component.getType());
    assertEquals(componentForeignSource, component.getForeignSource());
    assertEquals(componentForeignId, component.getForeignId());

    // Adding a copy of the event should not add to working memory
    engine.correlate(event2);

    memObjects = engine.getMemoryObjects();

    assertEquals("Unexpected size of workingMemory " + memObjects, 1, memObjects.size());

    eventObj = memObjects.get(0);

    assertTrue(componentEventClass.isInstance(eventObj));
    assertTrue(eventObj instanceof ComponentEvent);

    c = (ComponentEvent) eventObj;

    assertSame(event, c.getEvent());

    component = c.getComponent();
    assertEquals(componentType, component.getType());
    assertEquals(componentForeignSource, component.getForeignSource());
    assertEquals(componentForeignId, component.getForeignId());

}

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

/**
 * Parse an array that has only non-array children into a {@link Collection}.
 *
 * @param reader The reader to use, whose next token should either be {@link JsonToken#NULL} or
 * {@link JsonToken#BEGIN_ARRAY}./*from  w ww  . j a  v  a  2 s .c  o m*/
 * @param collection The Collection to populate. The parametrization should match {@code
 * typeClass}.
 * @param itemParser The parser to use for items of the array. May be null.
 * @param typeClass The type of items to expect in the array. May not be null, but may be
 * Object.class.
 * @param key The key corresponding to the current value. This is used to make more useful error
 * messages.
 */
private static <T> void parseFlatJsonArray(JsonReader reader, Collection<T> collection,
        JsonObjectParser<T> itemParser, Class<T> typeClass, String key) throws IOException {
    if (handleNull(reader)) {
        return;
    }

    Converter<T> converter = null;
    if (Converters.isConvertibleFromString(typeClass)) {
        converter = Converters.getConverter(typeClass);
    }

    final String discriminationName = ContextHolder.getContext().getSettings().getDiscriminationName();

    reader.beginArray();
    while (reader.hasNext()) {
        Object nextValue;
        final JsonToken nextToken = reader.peek();
        if (itemParser != null && nextToken == JsonToken.BEGIN_OBJECT) {
            reader.beginObject();
            nextValue = itemParser.parseJsonObject(null, reader, discriminationName, null);
            reader.endObject();
        } else if (converter != null && (nextToken == JsonToken.NUMBER || nextToken == JsonToken.STRING)) {
            nextValue = converter.convert(reader.nextString());
        } else {
            nextValue = parseNextValue(reader);
        }

        if (typeClass.isInstance(nextValue)) {
            // This is safe since we are calling class.isInstance()
            @SuppressWarnings("unchecked")
            T toAdd = (T) nextValue;
            collection.add(toAdd);
        } else {
            throw new IllegalStateException(
                    String.format(Locale.US, "Could not convert value in array at \"%s\" to %s from %s.", key,
                            typeClass.getCanonicalName(), getClassName(nextValue)));
        }
    }
    reader.endArray();
}

From source file:com.mac.tarchan.desktop.event.EventQuery.java

/**
 * ??????????/* w w  w. j  a  v  a 2 s  . co  m*/
 * 
 * @param type ???
 * @return ????
 */
public <T> List<T> list(Class<T> type) {
    ArrayList<T> sublist = new ArrayList<T>();
    for (Component child : list) {
        if (type.isInstance(child)) {
            sublist.add(type.cast(child));
        }
    }

    return sublist;
}