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:Main.java

private static <T extends View> T getFirstChildByInstance(ViewGroup parent, Class<T> instance) {
    View retView = null;//from w  w w . ja  v  a 2s  . co  m
    int childCount = parent.getChildCount();

    for (int childIndex = 0; childIndex < childCount; childIndex++) {
        View child = parent.getChildAt(childIndex);

        if (instance.isAssignableFrom(child.getClass())) {
            return instance.cast(child);
        }

        if (child instanceof ViewGroup) {
            View v = getFirstChildByInstance((ViewGroup) child, instance);

            if (v != null) {
                return instance.cast(v);
            }
        }
    }

    return instance.cast(retView);
}

From source file:org.echocat.jemoni.jmx.support.SpringUtils.java

@Nonnull
public static <T> T getBeanFor(@Nonnull ServletContext servletContext, @Nonnull String beanName,
        @Nonnull Class<T> beanType) throws ServletException {
    final Object applicationContext = getApplicationContext(servletContext);
    final Object plainBean;
    try {// ww  w. ja  va2  s . c o  m
        plainBean = beanType.cast(GET_BEAN.invoke(applicationContext, beanName));
    } catch (Exception e) {
        final Throwable target = e instanceof InvocationTargetException
                ? ((InvocationTargetException) e).getTargetException()
                : null;
        if (target != null && target.getClass().getName().endsWith("NoSuchBeanDefinitionException")) {
            throw new ServletException("Could not find bean '" + beanName + "' at " + applicationContext + ".",
                    target);
        } else {
            throw new ServletException(
                    "Could not retrieve bean '" + beanName + "' from " + applicationContext + ".",
                    target != null ? target : e);
        }
    }
    if (!beanType.isInstance(plainBean)) {
        throw new ServletException("Could bean '" + beanName + "' is of type " + plainBean.getClass().getName()
                + " not of expected " + beanType.getName() + ".");
    }
    return beanType.cast(plainBean);
}

From source file:edu.sdsc.scigraph.neo4j.GraphUtil.java

/***
 * Get a single valued property in a type-safe way.
 * /*from   w  w w.j  a v a2 s .c  om*/
 * @param container the {@link PropertyContainer} in question
 * @param property the name of the property
 * @param type the expected type of the property
 * @return an {@link Optional} property value
 * @throws ClassCastException if {@code type} does not match the actual type in the graph
 */
static public <T> Optional<T> getProperty(PropertyContainer container, String property, Class<T> type) {
    Optional<T> value = Optional.<T>absent();
    if (container.hasProperty(property)) {
        value = Optional.<T>of(type.cast(container.getProperty(property)));
    }
    return value;
}

From source file:Main.java

public static <T> T generateRandom(Class<T> objectClass) {
    Random r = new Random();
    if (objectClass.equals(String.class)) {
        String s = "";
        for (int i = 0; i < 10; i++) {
            char c = (char) (Math.abs(r.nextInt()) % ('Z' - 'A') + 'A');
            s = s + c;/*from w ww.  j  a v  a 2 s . c o m*/
        }
        return objectClass.cast(s);
    } else if (objectClass.equals(Integer.class)) {
        Integer s = r.nextInt();
        return objectClass.cast(s);
    } else if (objectClass.equals(Long.class)) {
        Long s = r.nextLong();
        return objectClass.cast(s);
    } else if (objectClass.equals(java.util.Date.class)) {
        java.util.Calendar c = java.util.Calendar.getInstance();
        c.set(java.util.Calendar.MONTH, Math.abs(r.nextInt()) % 12);
        c.set(java.util.Calendar.DAY_OF_MONTH, Math.abs(r.nextInt()) % 30);
        return objectClass.cast(c.getTime());
    }
    return null;
}

From source file:Main.java

@SuppressWarnings("unchecked")
public static <T> Object xmlToObject(InputStream xmlContent, Class<T> clazz) throws JAXBException {

    JAXBContext context = JAXBContext.newInstance(clazz);
    Unmarshaller unmarshaller = context.createUnmarshaller();
    unmarshaller.setSchema(null); //note: setting schema to null will turn validator off
    Object unMarshalled = unmarshaller.unmarshal(xmlContent);
    Object xmlObject = clazz.cast(unMarshalled);

    return (T) xmlObject;
}

From source file:com.ikanow.aleph2.logging.utils.LoggingUtils.java

/**
 * Returns the value in message.details.get(field) or any part of the access does not exist.
 * @param <T>/*  w  w w . j ava 2  s.co  m*/
 * 
 * @param message
 * @param field
 * @param clazz 
 * @return
 */
public static <T> T getDetailsMapValue(final BasicMessageBean message, final String field,
        final Class<T> clazz) {
    return Optional.ofNullable(message).map(m -> m.details()).map(d -> d.get(field)).map(r -> clazz.cast(r))
            .orElse(null);
}

From source file:com.infinities.skyport.timeout.ServiceProviderTimeLimiter.java

private static <T> T newProxy(Class<T> interfaceType, InvocationHandler handler) {
    Object object = Proxy.newProxyInstance(interfaceType.getClassLoader(), new Class<?>[] { interfaceType },
            handler);/*from  w  w w  . j  a v  a 2 s . co m*/
    return interfaceType.cast(object);
}

From source file:com.snapdeal.archive.util.ArchivalUtil.java

/**
 * Returns a map where key is of type K and value is object. 
 * @param objects//from   w ww. ja  v  a2s .  c o  m
 * @param propertyName
 * @return
 */
public static <K, T> Map<K, T> getPropertyObjectMap(Set<T> objects, String propertyName,
        Class<K> propertyClass) {
    Map<K, T> propertyObjectMap = new HashMap<>();
    for (T t : objects) {
        Object value = null;
        try {
            value = PropertyUtils.getProperty(t, propertyName);
            K k = (K) propertyClass.cast(value);
            propertyObjectMap.put(k, t);
        } catch (IllegalAccessException | InvocationTargetException | NoSuchMethodException e) {
            e.printStackTrace();
        }
    }
    return propertyObjectMap;
}

From source file:net.darkmist.alib.io.Serializer.java

/** Read one serialized object from a input stream.
 * @param in InputStream to read from. This will be closed!
 * @param type The type that is to be read.
 * @return The serialized object cast as type.
 *//*from  w w  w . ja v a 2s  .com*/
public static <T extends Serializable> T deserializeFromStream(InputStream in, Class<T> type)
        throws ClassNotFoundException, IOException {
    ObjectInputStream objIn;
    T obj;

    if (in instanceof ObjectInputStream)
        objIn = (ObjectInputStream) in;
    else
        objIn = new ObjectInputStream(in);

    obj = type.cast(objIn.readObject());
    // to close or not to close... That is the question...
    // we close... It doesn't make too much sense to have a stream with more afterwards...There would be two
    // stream headers...
    objIn.close();
    return obj;
}

From source file:com.sforce.cd.apexUnit.client.codeCoverage.WebServiceInvoker.java

public static <T> Set<T> castSet(Class<? extends T> clazz, Collection<?> c) {
    Set<T> set = new HashSet<T>();
    for (Object o : c)
        set.add(clazz.cast(o));
    return set;//from   w w  w  .ja va  2  s.co  m
}