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.britesnow.snow.web.RequestContext.java

@SuppressWarnings("unchecked")
public <T> T getUser(Class<T> userClass) {
    if (authToken != null && userClass.isInstance(authToken.getUser())) {
        return (T) authToken.getUser();
    } else {/*  www .  jav a2s .  co m*/
        return null;
    }
}

From source file:com.l2jfree.gameserver.templates.StatsSet.java

/**
 * Returns an enumeration of &lt;T&gt; from the set. If the enumeration is empty, the method returns the value of the parameter "deflt".
 * /*from w  ww . ja v  a  2 s.c o m*/
 * @param <T> : Class of the enumeration returned
 * @param name : String designating the key in the set
 * @param enumClass : Class designating the class of the value associated with the key in the set
 * @param deflt : <T> designating the value by default
 * @return Enum<T>
 */
@SuppressWarnings("unchecked")
public final <T extends Enum<T>> T getEnum(String name, Class<T> enumClass, T deflt) {
    Object val = get(name);
    if (val == null)
        return deflt;
    if (enumClass.isInstance(val))
        return (T) val;
    try {
        return Enum.valueOf(enumClass, String.valueOf(val));
    } catch (Exception e) {
        throw new IllegalArgumentException(
                "Enum value of type " + enumClass.getName() + "required, but found: " + val);
    }
}

From source file:org.opencb.commons.datastore.core.ObjectMap.java

public <T> T get(final String field, final Class<T> clazz, T defaultValue) {
    if (objectMap.containsKey(field)) {
        Object obj = objectMap.get(field);
        if (clazz.isInstance(obj)) {
            return clazz.cast(obj);
        }/*  w  ww.ja  v a  2s.c o m*/
    }
    return defaultValue;
}

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

/**
 * Returns the annotation with the highest end offset of type <tt>cls</tt> overlapping <tt>focusAnnotation</tt>.
 * <p>//from  w  w w.jav  a2 s.c  o m
 * This method is very similar to {@link #getNearestOverlappingAnnotations(JCas, Annotation, Class)}. Actually, the
 * last result element of {@link #getNearestOverlappingAnnotations(JCas, Annotation, Class)} equals the returned
 * annotation from this method.
 * </p>
 * 
 * @param aJCas
 * @param focusAnnotation
 * @param cls
 * @return
 */
@SuppressWarnings("unchecked")
public static <T extends Annotation> T getLastOverlappingAnnotation(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();

    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()) {
            return (T) currentAnnotation;
        }
        cursor.moveToPrevious();
    }
    return null;
}

From source file:org.openlmis.fulfillment.web.BaseWebIntegrationTest.java

<T> List<T> getPageContent(Page page, Class<T> type) {
    List content = page.getContent();

    if (isEmpty(content)) {
        // nothing to do
        return Collections.emptyList();
    }//  w  w w .  j a  v  a 2  s  . c  o m

    if (type.isInstance(content.get(0))) {
        // content contains instances of the given type
        return Collections.checkedList(content, type);
    }

    if (content.get(0) instanceof Map) {
        // jackson does not convert json to correct type
        // instead it use default operation and objects are
        // represented by Map

        // We have to do manually convert map to the given type =(
        ObjectMapper mapper = new ObjectMapper();
        mapper.findAndRegisterModules();

        TypeFactory factory = mapper.getTypeFactory();
        CollectionLikeType collectionType = factory.constructCollectionLikeType(List.class, type);

        return mapper.convertValue(content, collectionType);
    }

    throw new IllegalStateException("the page content contains unsupported type");
}

From source file:com.eucalyptus.images.Images.java

private static <R, T, TT> Function<T, R> typedFunction(final Function<TT, R> typeSpecificFunction,
        final Class<TT> subClass, @Nullable final R defaultValue) {
    return new Function<T, R>() {
        @Override//from  ww w. j  a v a2 s .  co m
        public R apply(final T parameter) {
            return subClass.isInstance(parameter) ? typeSpecificFunction.apply(subClass.cast(parameter))
                    : defaultValue;
        }
    };
}

From source file:com.amazon.carbonado.repo.replicated.ReplicatedRepository.java

@SuppressWarnings("unchecked")
public <C extends Capability> C getCapability(Class<C> capabilityType) {
    if (capabilityType.isInstance(this)) {
        if (ShutdownCapability.class.isAssignableFrom(capabilityType)) {
            if (mReplicaRepository.getCapability(capabilityType) == null
                    && mMasterRepository.getCapability(capabilityType) == null) {

                return null;
            }/*from w w w  . j a v a  2s  .  com*/
        }
        return (C) this;
    }

    // Favor replica's indexing capabilities, since they are used for queries.
    boolean favorReplica = IndexInfoCapability.class.isAssignableFrom(capabilityType)
            || IndexEntryAccessCapability.class.isAssignableFrom(capabilityType);

    C masterCap = mMasterRepository.getCapability(capabilityType);
    C replicaCap = mReplicaRepository.getCapability(capabilityType);

    if (favorReplica) {
        return replicaCap != null ? replicaCap : masterCap;
    } else {
        return masterCap != null ? masterCap : replicaCap;
    }
}

From source file:com.jaspersoft.jasperserver.remote.services.impl.PermissionsServiceImpl.java

protected List<ObjectPermission> filterByType(List<ObjectPermission> data, Class<?> recipientType) {
    List<ObjectPermission> result = new LinkedList<ObjectPermission>();
    for (ObjectPermission permission : data) {
        if (recipientType.isInstance(permission.getPermissionRecipient())) {
            result.add(permission);/*from ww w  . j  a va 2s . co  m*/
        }
    }
    return result;
}

From source file:at.jku.rdfstats.RDFStatsModelImpl.java

/**
 * constructor/*from w  ww  .j a v  a 2 s.  c  o m*/
 * @param model
 */
@SuppressWarnings("unchecked")
protected RDFStatsModelImpl(Model model) {
    this.model = model;
    this.cachedHistograms = new Hashtable<Integer, Histogram<?>>();

    // sync TDB models upon initialization
    try {
        Class graphTDB = Class.forName("com.hp.hpl.jena.tdb.store.GraphTDB");
        try {
            if (graphTDB.isInstance(this.model.getGraph())) {
                Class classTDB = Class.forName("com.hp.hpl.jena.tdb.TDB");
                Method sync = classTDB.getMethod("sync", new Class[] { Model.class });
                sync.invoke(null, new Object[] { model });
            }
        } catch (Exception e) {
            log.error("Failed to sync TDB model.", e);
        }
    } catch (Exception ignore) {
    }

    log.debug("RDFStatsModel created from existing model.");
}

From source file:org.nabucco.alfresco.enhScriptEnv.common.script.aop.ScriptableMapListAdapterInterceptor.java

/**
 * {@inheritDoc}/*from  w  w w  .j  av  a  2 s  . c  om*/
 */
@Override
public Object invoke(final MethodInvocation invocation) throws Throwable {
    final Object result;
    final Method method = invocation.getMethod();
    final Class<?> declaringClass = method.getDeclaringClass();
    if (Scriptable.class.equals(declaringClass) && invocation instanceof ProxyMethodInvocation) {
        final ProxyMethodInvocation pInvocation = (ProxyMethodInvocation) invocation;
        final Object proxy = pInvocation.getProxy();

        final String methodName = method.getName();
        final Object[] arguments = invocation.getArguments();
        final Class<?>[] parameterTypes = method.getParameterTypes();

        boolean redirect = false;
        String redirectMethod = null;
        Object[] redirectParams = null;
        @SuppressWarnings("rawtypes")
        Class[] redirectParamTypes = null;
        Class<?> redirectDeclaringClass = null;
        Object nonRedirectResult = null;

        // String-switch not supported in Java < 8
        switch (ScriptableMethodName.methodLiteralOf(methodName)) {
        case GET:
            if (proxy instanceof List<?> && int.class.equals(parameterTypes[0])) {
                redirect = true;
                redirectDeclaringClass = List.class;
                redirectMethod = "get";
                redirectParams = new Object[] { arguments[0] };
                redirectParamTypes = new Class[] { parameterTypes[0] };
            } else if (proxy instanceof Map<?, ?>) {
                redirect = true;
                redirectDeclaringClass = Map.class;
                redirectMethod = "get";
                redirectParams = new Object[] { arguments[0] };
                redirectParamTypes = new Class[] { Object.class };
            }
            break;
        case HAS:
            if (proxy instanceof List<?> && int.class.equals(parameterTypes[0])) {
                nonRedirectResult = Boolean
                        .valueOf(((Integer) arguments[0]).intValue() < ((List<?>) proxy).size());
            } else if (proxy instanceof Map<?, ?>) {
                redirect = true;
                redirectDeclaringClass = Map.class;
                redirectMethod = "containsKey";
                redirectParams = new Object[] { arguments[0] };
                redirectParamTypes = new Class[] { Object.class };
            }
            break;
        case PUT:
            if (proxy instanceof List<?> && int.class.equals(parameterTypes[0])) {
                redirect = true;
                redirectDeclaringClass = List.class;
                redirectMethod = ((List<?>) proxy).size() > ((Integer) arguments[0]).intValue() ? "set" : "add";
                redirectParams = new Object[] { arguments[0], arguments[2] };
                redirectParamTypes = new Class[] { int.class, Object.class };
            } else if (proxy instanceof Map<?, ?>) {
                redirect = true;
                redirectDeclaringClass = Map.class;
                redirectMethod = "put";
                redirectParams = new Object[] { arguments[0], arguments[2] };
                redirectParamTypes = new Class[] { Object.class, Object.class };
            }
            break;
        case DELETE:
            if (proxy instanceof List<?> && int.class.equals(parameterTypes[0])) {
                redirect = true;
                redirectDeclaringClass = List.class;
                redirectMethod = "remove";
                redirectParams = arguments;
                redirectParamTypes = parameterTypes;
            } else if (proxy instanceof Map<?, ?>) {
                redirect = true;
                redirectDeclaringClass = Map.class;
                redirectMethod = "remove";
                redirectParams = arguments;
                redirectParamTypes = new Class[] { Object.class };
            }
            break;
        case GETIDS:
            if (proxy instanceof Map<?, ?>) {
                // Note: we do not cover the case of Map + List for getIds, as List is typically only used for indexed access based on
                // known size and not retrieval of keys
                nonRedirectResult = ((Map<?, ?>) proxy).keySet().toArray(new Object[0]);
            } else if (proxy instanceof List<?>) {
                final int size = ((List<?>) proxy).size();
                final Object[] arr = new Object[size];
                for (int idx = 0; idx < size; idx++) {
                    arr[idx] = Integer.valueOf(idx);
                }
            }
            break;
        default:
            // NO-OP
            break;
        }

        final Class<?> returnType = method.getReturnType();
        if (redirect && redirectDeclaringClass != null) {
            final Method redirectMethodHandle = redirectDeclaringClass.getMethod(redirectMethod,
                    redirectParamTypes);
            result = redirectMethodHandle.invoke(proxy, redirectParams);
        } else if (void.class.equals(returnType)) {
            result = null;
        } else if (nonRedirectResult != null && returnType.isInstance(nonRedirectResult)) {
            result = nonRedirectResult;
        } else if (boolean.class.equals(returnType)) {
            result = nonRedirectResult instanceof Boolean ? (Boolean) nonRedirectResult : Boolean.FALSE;
        } else {
            // TODO: what else to do?
            result = null;
        }
    } else {
        result = invocation.proceed();
    }

    return result;
}