Example usage for java.lang Class cast

List of usage examples for java.lang Class cast

Introduction

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

Prototype

@SuppressWarnings("unchecked")
@HotSpotIntrinsicCandidate
public T cast(Object obj) 

Source Link

Document

Casts an object to the class or interface represented by this Class object.

Usage

From source file:com.flexive.faces.FxJsfUtils.java

/**
 * Find a parent of the given class. Throws a runtime exception if none is found.
 *
 * @param component the (child) component that searches an ancestor
 * @param cls       the class or interface to be searched for in the component's ancestors
 * @return the parent component/*  w w w  .  j a v a  2 s  . co  m*/
 */
public static <T> T findAncestor(UIComponent component, Class<T> cls) {
    UIComponent current = component;
    if (current != null) {
        current = current.getParent();
    }
    while (current != null && !(cls.isAssignableFrom(current.getClass()))) {
        current = current.getParent();
    }
    if (current == null) {
        throw new FxNotFoundException(LOG, "ex.jsf.ancestor.notFound").asRuntimeException();
    }
    return cls.cast(current);
}

From source file:net.camelpe.extension.camel.spi.CdiRegistry.java

/**
 * @see org.apache.camel.spi.Registry#lookup(java.lang.String,
 *      java.lang.Class)// ww w.j a va  2s  .c  o m
 */
@Override
public <T> T lookup(final String name, final Class<T> type) {
    Validate.notEmpty(name, "name");
    Validate.notNull(type, "type");
    getLog().trace("Looking up bean using name = [{}] having expected type = [{}] in CDI registry ...", name,
            type.getName());

    return type.cast(lookup(name));
}

From source file:de.decoit.simu.cbor.ifmap.deserializer.ExtendedIdentifierDeserializerManager.java

/**
 * Deserialize an object of the specified class from the specified data items.
 * The attributes and nested tags arrays may be empty but never null.
 *
 * @param <T> Type of the object to be deserialized, must be a subclass of {@link AbstractExtendedIdentifier}
 * @param namespace CBOR data item representing the element namespace
 * @param cborName CBOR data item representing the element name
 * @param attributes CBOR array data item containing the element's attributes
 * @param nestedTags CBOR array data item containing the element's nested tags
 * @param identifierType Type of the object to be deserialized
 * @return The deserialized object//from  w  w  w . ja v a 2 s.com
 * @throws CBORDeserializationException if deserialization failed
 */
public static <T extends AbstractExtendedIdentifier> T deserialize(final DataItem namespace,
        final DataItem cborName, final Array attributes, final Array nestedTags, final Class<T> identifierType)
        throws CBORDeserializationException {
    if (namespace == null) {
        throw new IllegalArgumentException("Namespace must not be null");
    }

    if (cborName == null) {
        throw new IllegalArgumentException("CBOR name must not be null");
    }

    if (attributes == null) {
        throw new IllegalArgumentException("Attributes array must not be null");
    }

    if (nestedTags == null) {
        throw new IllegalArgumentException("Nested tags array must not be null");
    }

    if (identifierType == null) {
        throw new IllegalArgumentException("Target identifier type must not be null");
    }

    try {
        // If default deserializers were not registered yet, do so
        if (!initialized) {
            init();
        }

        // Check if a deserializer for this type was registered
        if (hasVendorDeserializer(identifierType)) {
            DictionarySimpleElement elementEntry = getTopLevelElement(namespace, cborName);

            return identifierType.cast(registeredDeserializers.get(identifierType).deserialize(attributes,
                    nestedTags, elementEntry));
        }

        // If no deserializer was found, fail with exception
        throw new UnsupportedOperationException(
                "Cannot deserialize class: " + identifierType.getCanonicalName());
    } catch (RuntimeException ex) {
        throw new CBORDeserializationException(
                "RuntimeException during deserialization, see nested exception" + "for details", ex);
    }
}

From source file:hudson.Util.java

/**
 * Creates a filtered sublist./*from  www.  jav a 2s. c  om*/
 * @since 1.176
 */
public static <T> List<T> filter(Iterable<?> base, Class<T> type) {
    List<T> r = new ArrayList<T>();
    for (Object i : base) {
        if (type.isInstance(i)) {
            r.add(type.cast(i));
        }
    }
    return r;
}

From source file:im.r_c.android.fusioncache.MemCache.java

/**
 * Special get method./*from w  w  w.ja v  a 2  s .c o  m*/
 * Get value by class passed in.
 * <p>
 * Only used in this package.
 */
synchronized <T> T get(String key, Class<T> clz) {
    ValueWrapper wrapper = mCacheWrapper.get(key);
    if (wrapper == null || !clz.isInstance(wrapper.obj)) {
        return null;
    }
    return clz.cast(wrapper.obj);
}

From source file:hudson.tasks.junit.TestObject.java

public <T> T getTestAction(Class<T> klazz) {
    for (TestAction action : getTestActions()) {
        if (klazz.isAssignableFrom(action.getClass())) {
            return klazz.cast(action);
        }//from  w ww.  j  av a 2 s. c o  m
    }
    return null;
}

From source file:org.solmix.runtime.support.spring.SpringResourceResolver.java

@Override
public <T> T resolve(String resourceName, Class<T> resourceType) {

    try {/*  w  ww.j  a  v a  2  s.  c  o m*/
        T resource = null;
        if (resourceName == null) {
            String names[] = context.getBeanNamesForType(resourceType);
            if (names != null && names.length > 0) {
                resource = resourceType.cast(context.getBean(names[0], resourceType));
            }
        } else {
            resource = resourceType.cast(context.getBean(resourceName, resourceType));
        }
        return resource;
    } catch (NoSuchBeanDefinitionException def) {
        //ignore
    }
    try {
        if (ClassLoader.class.isAssignableFrom(resourceType)) {
            return resourceType.cast(context.getClassLoader());
        } else if (URL.class.isAssignableFrom(resourceType)) {
            Resource r = context.getResource(resourceName);
            if (r != null && r.exists()) {
                r.getInputStream().close(); //checks to see if the URL really can resolve
                return resourceType.cast(r.getURL());
            }
        }
    } catch (IOException e) {
        //ignore
    }
    return null;
}

From source file:org.apache.servicemix.nmr.management.ManagementAgent.java

/**
 * @see org.fusesource.commons.management.ManagementStrategy#getManagedObjectName(java.lang.Object,java.lang.String,java.lang.Class)
 *///from w  w w .  ja  v a  2  s .co m
public <T> T getManagedObjectName(Object managableObject, String customName, Class<T> nameType)
        throws Exception {
    return String.class.equals(nameType) && managableObject == null && customName == null
            ? nameType.cast(namingStrategy.getJmxDomainName())
            : ObjectName.class.equals(nameType)
                    ? nameType.cast(getTypeSpecificObjectName(managableObject, customName))
                    : null;
}

From source file:org.thingsplode.synapse.core.AbstractMessage.java

public <E> E expectBody(Class<E> type) throws MarshallerException {
    //todo: review if it makes sense
    if (body == null) {
        throw new MarshallerException("This message has not extension.", HttpStatus.EXPECTATION_FAILED);
    }/*from  w  ww  .  java  2 s  .co m*/
    try {
        return type.cast(body);
    } catch (ClassCastException ex) {
        throw new MarshallerException(
                "The expected message is not type of " + type.getSimpleName() + ": " + ex.getMessage(),
                HttpStatus.EXPECTATION_FAILED, ex);
    }
}

From source file:com.adobe.acs.tools.csv_asset_importer.impl.Column.java

protected <T> T toObjectType(String data, Class<T> klass) {
    data = StringUtils.trim(data);/*from   w  w w .  jav a  2s .co m*/

    if (Double.class.equals(klass)) {
        try {
            return klass.cast(Double.parseDouble(data));
        } catch (NumberFormatException ex) {
            return null;
        }
    } else if (Long.class.equals(klass)) {
        try {
            return klass.cast(Long.parseLong(data));
        } catch (NumberFormatException ex) {
            return null;
        }
    } else if (Integer.class.equals(klass)) {
        try {
            return klass.cast(Long.parseLong(data));
        } catch (NumberFormatException ex) {
            return null;
        }
    } else if (StringUtils.equalsIgnoreCase("true", data) && Boolean.class.equals(klass)) {
        return klass.cast(Boolean.TRUE);
    } else if (StringUtils.equalsIgnoreCase("false", data) && Boolean.class.equals(klass)) {
        return klass.cast(Boolean.FALSE);
    } else if (Date.class.equals(klass) || Calendar.class.equals(klass)) {
        return klass.cast(ISODateTimeFormat.dateTimeParser().parseDateTime(data).toCalendar(Locale.US));
    } else {
        return klass.cast(data);
    }
}