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.jaspersoft.jasperserver.test.BaseRepositoryTestTestNG.java

protected Resource assertLocalReference(ResourceReference reference, Class type) {
    assertNotNull(reference);/*from   w ww.j  a v a2  s  .  co  m*/
    assertTrue(reference.isLocal());
    Resource res = reference.getLocalResource();
    assertNotNull(res);
    assertTrue(type.isInstance(res));
    return res;
}

From source file:com.architexa.diagrams.jdt.builder.ReloASTExtractor.java

/**
 * Returns the oldest parent that has the required type
 *//*w  ww  .ja  v  a  2 s.c  o m*/
public ASTNode getAncestor(Class<?> inst) {
    ASTNode retVal = null;
    Iterator<ASTNode> it = context.iterator();
    it.next(); // the first items is itself, the second one is parent
    while (it.hasNext()) {
        ASTNode node = it.next();
        if (inst.isInstance(node)) {
            retVal = node;
        }
    }
    return retVal;
}

From source file:net.freedom.gj.beans.factory.ext.SpringTreeBeanFactory.java

@Override
protected List<Object> findAllByType(Class type) {
    List<Object> list = new ArrayList<Object>();
    Map<String, Object> objects = BeanFactoryUtils
            .beansOfTypeIncludingAncestors((ListableBeanFactory) beanFactory, type);

    for (String key : objects.keySet()) {
        if (objects.get(key).getClass().isAnnotationPresent(Criteria.class)
                || objects.get(key).getClass().isAnnotationPresent(CriteriaList.class)
                || type.isInstance(objects.get(key))) {
            list.add(objects.get(key));/*w ww  .ja v  a 2 s  .co  m*/
        }
    }
    return list;
}

From source file:com.opengamma.integration.marketdata.manipulator.dsl.SimulationScript.java

/**
 * Defines a method in the DSL taking a block to define the script parameters and their types. It checks the
 * parameters are available in the script's binding and that they have the expected type.
 * <pre>//from   ww  w  . ja v a2  s .co m
 * parameters {
 *   foo String
 *   bar Number
 * }
 * </pre>
 * @param body The block that defines the script's parameters
 */
public void parameters(Closure body) {
    ParametersDelegate parametersDelegate = new ParametersDelegate();
    body.setDelegate(parametersDelegate);
    body.setResolveStrategy(Closure.DELEGATE_FIRST);
    body.call();
    // check the parameters are all in the binding and have the expected types
    Binding binding = getBinding();
    Map<String, Class<?>> parameters = parametersDelegate.getParameters();
    for (Map.Entry<String, Class<?>> entry : parameters.entrySet()) {
        String varName = entry.getKey();
        Class<?> varType = entry.getValue();
        if (!binding.hasVariable(varName)) {
            throw new DataNotFoundException("Parameter named " + varName + " not found");
        }
        Object varValue = binding.getVariable(varName);
        if (!varType.isInstance(varValue)) {
            throw new IllegalArgumentException("Parameter " + varName + " has type "
                    + varValue.getClass().getName() + ", " + "required type is " + varType.getName());
        }
    }
}

From source file:com.jredrain.dao.BeanResultTransFormer.java

/**
 * ??Setter/*  w ww.j  a v  a  2 s . co m*/
 *
 * @param data
 * @param name
 * @param value
 * @throws Exception
 */
protected void handle(T data, String name, Object value) throws Exception {
    //
    if (value == null)
        return;
    List<Setter> setterList = setters.get(name.toLowerCase());
    if (setterList == null || setterList.isEmpty())
        return;
    //setter
    if (setterList.size() == 1) {
        Setter setter = setterList.get(0);
        if (value != null && !setter.type.isInstance(value)) {
            value = ConvertUtils.convert(value, setter.type);
        }
        setter.invoke(data, value);
        return;
    }
    //?
    List<Setter> compatibleList = new ArrayList<Setter>();
    //?
    List<Setter> numericList = new ArrayList<Setter>();
    for (Setter setter : setterList) {
        Class<?> type = setter.type;
        //?
        if (value != null && type == value.getClass()) {
            setter.invoke(data, value);
        }
        //?
        if (type.isInstance(value)) {
            compatibleList.add(setter);
        } else if (Number.class.isAssignableFrom(type) && value instanceof Number) {//?
            numericList.add(setter);
        }
    }
    if (compatibleList.size() == 1) {
        compatibleList.get(0).invoke(data, value);
        return;
    }
    if (compatibleList.isEmpty() && numericList.size() == 1) {
        value = ConvertUtils.convert(value, numericList.get(0).type);
        numericList.get(0).invoke(data, value);
        return;
    }
    if (compatibleList.size() > 0 || numericList.size() > 0) {
        throw new Exception("ambiguous setter methods to call");
    }
}

From source file:fi.tut.fast.MulticastProducer.java

@Override
protected void doStart() throws Exception {
    super.doStart();

    InetAddress addr = null;//  w ww. j  a v a  2 s  . c om
    Class addrClass;
    if (endpoint.getMulticastGroup() instanceof Inet4Address) {
        addrClass = Inet4Address.class;
    } else {
        addrClass = Inet6Address.class;
    }

    for (Enumeration<InetAddress> as = endpoint.getInterface().getInetAddresses(); as.hasMoreElements();) {
        InetAddress a = as.nextElement();
        if (addrClass.isInstance(a)) {
            addr = a;
        }
    }

    if (addr == null) {
        addr = endpoint.getInterface().getInetAddresses().nextElement();
    }

    LOG.info(String.format("Starting Producer Endpoint on interface %s (%s) ",
            endpoint.getInterface().getDisplayName(), addr.getHostAddress()));

    s = new MulticastSocket(new InetSocketAddress(addr.getHostAddress(), endpoint.getSourcePort()));
    s.setReuseAddress(true);
    s.setNetworkInterface(endpoint.getInterface());
    s.setLoopbackMode(true);
    //      s.setBroadcast(true);

    //      s.joinGroup(endpoint.getMulticastGroup());
    //      s.connect(endpoint.getMulticastGroup(), endpoint.getAddress().getPort());
    //      s.bind(new InetSocketAddress(endpoint.getMulticastGroup(), 0));
}

From source file:com.architexa.diagrams.jdt.builder.ReloASTExtractor.java

public int getContextDistance(Class<?> inst) {
    int cnt = 0;//  w  w w  . j  a v  a 2 s. c  o m
    Iterator<ASTNode> it = context.iterator();
    it.next(); // the first items is itself, the second one is parent
    while (it.hasNext()) {
        ASTNode node = it.next();
        cnt++;
        if (inst.isInstance(node)) {
            return cnt;
        }
    }
    return -1;
}

From source file:moe.encode.airblock.commands.core.components.ComponentBag.java

/**
 * <p>Calls the component method.</p>
 * <p>/*from www  .j  av  a 2s  . co m*/
 *     Please note that external components are prioritized as they may implement better
 *     suited algorithms for the actual plugin.
 * </p>
 * @param cls     The interface class that is implemented.
 * @param method  The method.
 * @param handle  The handle.
 * @param objects The parameters.
 * @param <T> The types.
 * @return The result of the call.
 */
@Nullable
public <T> T call(@NonNull Class<?> cls, @NonNull Method method, @NonNull HandleWrapper<?> handle,
        Object... objects) throws Throwable {
    Handle<?> hObj = handle.getHandle();
    if (this.methods.containsKey(cls))
        return this.callExternal(cls, method, handle.getEnvironment(), hObj, objects);
    else if (cls.isInstance(hObj))
        return this.callInternal(method, handle.getEnvironment(), hObj, objects);
    else
        throw new UnsupportedOperationException("Interface has not been implemented.");
}

From source file:edu.byu.softwareDistribution.web.workflow.Licenses.java

private <L extends License> List<License> extract1(final Class<License> klass) {
    if (licenses == null || licenses.isEmpty())
        return new ArrayList<License>(0);
    final List<License> result = new ArrayList<License>(licenses.size());
    for (final License l : licenses) {
        if (klass.isInstance(l)) {
            result.add(l);/*  w  ww  .ja  v a  2s  .  co  m*/
        }
    }
    return result;
}

From source file:com.solace.ExceptionHandler.java

/**
 * internal invocation point//from   w w  w . j  a  v  a 2 s  . c o  m
 * <ol>
 * <li>fire first on exact matches of Targeted, class focused, exceptions</li>
 * <li>fire on sub-typed targeted matches</li>
 * <li>fire on exact matches on defaults</li>
 * <li>fire on sub-typed matches on defaults</li>
 * </ol>
 * 
 * @param sender
 *            the instance that sent it. Can later be cast to a typed
 *            instance for method invocations (e.g. rollback)
 * @param msg
 *            message to be output if needed
 * @param e
 *            the actual exception that was thrown
 * @param data
 *            additional data
 */
private void handleException(Object sender, String msg, Exception e, Object... data) {
    IExceptionHandler handler = null;

    // we may have a null handler stack if we just want to get log output
    if (m_handlers != null) {
        // mapped by class, not instance
        if ((handler = m_handlers.get(e.getClass())) != null) {
            m_logger.info("Invoking exact targeted ExceptionHandler: [{}] against [{}]", handler.getClass(),
                    e.getClass());
            handler.handle(sender, msg, e, data);
        }

        // now let's fire all subtyped targeted handlers
        for (Class<? extends Exception> c : m_handlers.keySet()) {
            if (!classesAreEqual(c, e.getClass()) && c.isInstance(e)) {
                handler = m_handlers.get(c);
                m_logger.info("Invoking sub-typed targeted ExceptionHandler: [{}] for [{}] against [{}]",
                        handler.getClass(), c, e.getClass());
                handler.handle(sender, msg, e, data);
            }
        }
    }

    // load synchronized default IExcepwtionHandler base
    // for exception chaining
    if (m_defaults != null) {
        // if we have an exact match we fire first on defaults
        if ((handler = m_defaults.get(e)) != null) {
            m_logger.info("Invoking exact default ExceptionHandler: [{}] against [{}]", handler.getClass(),
                    e.getClass());
            handler.handle(sender, msg, e, data);
        }

        // for each default
        for (Class<? extends Exception> c : m_defaults.keySet()) {
            // is the exception an instance of a default
            if (!classesAreEqual(c, e.getClass()) && c.isInstance(e)) {
                handler = m_defaults.get(c);
                // if so invoke the default hander
                m_logger.info("Invoking subtyped default ExceptionHandler: [{}] for [{}] against [{}]",
                        handler.getClass(), c, e.getClass());
                handler.handle(sender, msg, e, data);
            }
        }
    }
}