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

/**
 * Returns a list of objects of <code>expectedType</code> contained in the given <code>collection</code>. Any
 * objects in the collection that are not assignable to the given <code>expectedType</code> are filtered out.
 * <p>//  w w w . java2s.c o  m
 * The order of the items in the list is the same as the order they were provided by the collection. The given
 * <code>collection</code> remains unchanged by this method.
 * <p>
 * If the given collection is null, en empty list is returned.
 *
 * @param collection   An iterable (e.g. Collection) containing the unfiltered items.
 * @param expectedType The type items in the returned List must be assignable to.
 * @param <T>          The type items in the returned List must be assignable to.
 * @return a list of objects of <code>expectedType</code>. May be empty, but never <code>null</code>.
 */

public static <T> List<T> filterByType(Iterable<?> collection, Class<T> expectedType) {
    List<T> filtered = new LinkedList<>();
    if (collection != null) {
        for (Object item : collection) {
            if (item != null && expectedType.isInstance(item)) {
                filtered.add(expectedType.cast(item));
            }
        }
    }
    return filtered;
}

From source file:com.feedzai.fos.common.validation.ValidationUtils.java

/**
 * Gets an <code>object instance</code> from the given configuration.
 *
 * @param configuration the configuration where the parameter lies
 * @param parameterName the name of the parameter
 * @param clazz         the class that the parameter represents
 * @return the <code>object</code> instantiation using the no-args constructor
 * @throws IllegalArgumentException if the class was not found, if the instantiation was illegal, or if there was illegal access
 *//*www  .  ja  v a 2s .  c o  m*/
@NotNull
public static <T> T getInstance(Configuration configuration, @NotBlank String parameterName, Class<T> clazz) {
    String classname = getStringNotBlank(configuration, parameterName);

    try {
        return clazz.cast(Class.forName(classname).newInstance());
    } catch (ClassNotFoundException | InstantiationException | IllegalAccessException e) {
        throw new IllegalArgumentException(String.format(NOT_CLASS, classname, clazz.getName()), e);
    }
}

From source file:net.bican.wordpress.Main.java

private static void printItem(Object o, Class<?> cl) {
    cl.cast(o);
    System.out.println(((StringHeader) o).getStringHeader());
    System.out.println(o);/*w ww .j  av  a  2 s .c  om*/
}

From source file:com.chrischurchwell.jukeit.server.ServerHandler.java

public static <T> List<T> castList(Class<? extends T> clazz, Collection<?> c) {
    List<T> r = new ArrayList<T>(c.size());
    for (Object o : c)
        r.add(clazz.cast(o));
    return r;//from  ww w .  ja  v a 2  s  . co m
}

From source file:Main.java

public static <T> Object generateXML2Object(String str, Class cls) throws JAXBException {

    InputSource is;/*  w  ww  . j  a va  2s.c o  m*/
    Object obj = null;

    is = new InputSource(new StringReader(str));
    JAXBContext jaxbContext = JAXBContext.newInstance(cls);
    Unmarshaller jaxbUnmarshaller = jaxbContext.createUnmarshaller();
    obj = cls.cast(jaxbUnmarshaller.unmarshal(is));

    return obj;
}

From source file:Main.java

static Unsafe getSMU() {
    try {/*  ww w .  jav  a2  s.  c  o m*/
        return sun.misc.Unsafe.getUnsafe();
    } catch (SecurityException tryReflectionInstead) {
        // ignore
    }
    try {
        return java.security.AccessController.doPrivileged((PrivilegedExceptionAction<Unsafe>) () -> {
            Class<sun.misc.Unsafe> k = sun.misc.Unsafe.class;
            for (Field f : k.getDeclaredFields()) {
                f.setAccessible(true);
                Object x = f.get(null);
                if (k.isInstance(x))
                    return k.cast(x);
            }
            throw new NoSuchFieldError("the Unsafe");
        });
    } catch (java.security.PrivilegedActionException e) {
        throw new RuntimeException("Could not initialize intrinsics", e.getCause());
    }
}

From source file:Main.java

/**
 * Change the type of array of Objects to an array of objects of type
 * newClass./*from   w  ww.  java2 s.c  o m*/
 * 
 */
@SuppressWarnings("unchecked")
public static <T> T[] changeArrayType(Object[] array, Class<T> newClass) {

    ArrayList<T> newArray = new ArrayList<T>();

    for (int i = 0; i < array.length; i++) {
        // Only add those objects that can be cast to the new class
        if (newClass.isInstance(array[i])) {
            newArray.add(newClass.cast(array[i]));
        }
    }

    return newArray.toArray((T[]) Array.newInstance(newClass, 0));
}

From source file:asia.gkc.vneedu.utils.FilterUtil.java

/**
 * /*  ww w.j av a2s .  c  o  m*/
 * @param list -  
 * @param object - ?
 * @param <T> - 
 * @return ?
 */
public static <T> T exclude(List<String> list, T object) {
    Class<?> c = object.getClass();

    for (String fieldName : list) {
        Method[] methods = c.getDeclaredMethods();

        for (Method method : methods) {
            if (method.getName().equals(getMethodName(fieldName, "set"))) {
                Class<?> param_class = method.getParameterTypes()[0];
                try {
                    logger.info("Invoking: " + method.getName());
                    method.invoke(object, param_class.cast(null));
                    logger.info("Invoked: " + method.getName());
                } catch (IllegalAccessException e) {
                    logger.warn("IllegalAccessException");
                } catch (InvocationTargetException e) {
                    logger.warn("InvocationTargetException");
                }
            }
        }
    }

    return object;
}

From source file:com.sonymobile.backlogtool.Util.java

public static <T> List<T> castList(Class<? extends T> clazz, Collection<?> c) {
    List<T> r = new ArrayList<T>(c.size());
    for (Object o : c) {
        r.add(clazz.cast(o));
    }//from w ww.  j a  va 2  s  .com
    return r;
}

From source file:de.ovgu.featureide.core.typecheck.helper.FujiWrapper.java

/**
 * Iterates a abstract syntax tree, searching for ASTNodes of the specific
 * type/*from  w  w  w .  j ava 2  s.  c om*/
 * 
 * @param node
 *            the current node
 * @param type
 *            the node type to look for
 * @return a list of nodes of the given type
 */
@SuppressWarnings("rawtypes")
public static <T> List<T> getChildNodesByType(ASTNode node, Class<T> type) {
    List<T> list = new ArrayList<T>();
    for (int i = 0; i < node.getNumChild(); i++) {
        ASTNode c = node.getChild(i);
        if (type.isInstance(c)) {
            list.add(type.cast(c));
        }
        list.addAll(getChildNodesByType(c, type));
    }
    return list;
}