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.palantir.ptoss.util.Reflections.java

/**
 * Given an {@link Object} and a {@link Field} of a known {@link Class} type, get the field.
 * This will return the value of the field regardless of visibility modifiers (i.e., it will
 * return the value of private fields.)/*from  w w  w  .j  a v a2 s  .co m*/
 */
public static <T> T getFieldObject(Object object, Field field, Class<T> klass) {
    try {
        boolean accessible = field.isAccessible();
        field.setAccessible(true);
        Object fieldObject = field.get(object);
        field.setAccessible(accessible);
        return klass.cast(fieldObject);
    } catch (IllegalAccessException e) {
        // shouldn't happen since we set accessibility above.
        return null;
    }
}

From source file:org.wildfly.camel.test.hipchat.HipchatProducerIntegrationTest.java

public static <T> T assertIsInstanceOf(Class<T> expectedType, Object value) {
    Assert.assertNotNull("Expected an instance of type: " + expectedType.getName() + " but was null", value);
    Assert.assertTrue("Object should be of type " + expectedType.getName() + " but was: " + value
            + " with the type: " + value.getClass().getName(), expectedType.isInstance(value));
    return expectedType.cast(value);
}

From source file:com.shenit.commons.utils.DataUtils.java

/**
 * Parse to specific number type//  w  w  w. j a v  a  2 s . c o m
 * @param obj
 * @param defaultVal
 * @param clazz
 * @param func
 * @return
 */
public static <T> T parseToNumber(Object obj, T defaultVal, Class<T> clazz, Function<BigDecimal, T> func) {
    T result = defaultVal;
    if (obj == null)
        return defaultVal;
    if (obj.getClass().isAssignableFrom(clazz))
        return clazz.cast(obj);
    String objStr = obj.toString();
    try {
        result = func.apply(new BigDecimal(objStr));
    } catch (Exception ex) {
    }
    return result;
}

From source file:de.cebitec.readXplorer.util.GeneralUtils.java

/**
 * Converts a given number into a number of the given classType. If this is
 * not possible, it throws a ClassCastException
 * @param <T> one of the classes derived from Number
 * @param classType the type to convert the number into
 * @param number the number to convert//w w w  .ja v  a  2s.  co m
 * @return The converted number
 */
public static <T extends Number> T convertNumber(Class<T> classType, Number number) throws ClassCastException {
    T convertedValue = null;
    if (classType.equals(Integer.class)) {
        convertedValue = classType.cast(number.intValue());
    } else if (classType.equals(Double.class)) {
        convertedValue = classType.cast(number.doubleValue());
    } else if (classType.equals(Long.class)) {
        convertedValue = classType.cast(number.longValue());
    } else if (classType.equals(Float.class)) {
        convertedValue = classType.cast(number.floatValue());
    } else if (classType.equals(Short.class)) {
        convertedValue = classType.cast(number.shortValue());
    } else if (classType.equals(Byte.class)) {
        convertedValue = classType.cast(number.byteValue());
    }

    if (convertedValue == null) {
        throw new ClassCastException("Cannot cast the given number into the given format.");
    }

    return convertedValue;
}

From source file:Main.java

public static <K, V> Map<K, List<V>> copyNullSafeMultiHashMapReified(Class<V> valueType,
        Map<? extends K, List<?>> map) {
    if (valueType == null)
        throw new NullPointerException("valueType");
    if (map == null)
        throw new NullPointerException("map");

    @SuppressWarnings("unchecked")
    Map<K, List<V>> result = (Map<K, List<V>>) (Map<?, ?>) copyNullSafeMutableHashMap(map);
    for (Map.Entry<K, List<V>> entry : result.entrySet()) {
        List<V> value = entry.getValue();
        ArrayList<V> valueCopy = new ArrayList<V>(value);
        for (V element : valueCopy) {
            valueType.cast(element);
        }// w w  w.j  av a2s  .  co m

        entry.setValue(Collections.unmodifiableList(valueCopy));
    }
    return result;
}

From source file:Main.java

/**
 * Convert XML data to a bean using JAXB.
 * /*from www.j  a  va 2  s. c  o  m*/
 * @param b
 *            The bean, represented as XML.
 * @param implClass
 *            The implementation class of the bean.
 * @param bc
 *            Additional classes to add to the JAXB context.
 * @return The bean, unmarshalled from the XML data using JAXB.
 */
public static <T> T unmarshal(String b, Class<T> implClass, Class<?>... bc) {
    Class<?>[] bind;
    if (bc.length > 1) {
        bind = new Class<?>[bc.length + 1];
        bind[0] = implClass;
        for (int i = 0; i < bc.length; i++) {
            bind[i + 1] = bc[i];
        }
    } else {
        bind = new Class<?>[] { implClass, };
    }
    ByteArrayInputStream bais = new ByteArrayInputStream(b.getBytes());
    try {
        JAXBContext jaxbContext = JAXBContext.newInstance(bind);
        Unmarshaller unmarshaller = jaxbContext.createUnmarshaller();
        return implClass.cast(unmarshaller.unmarshal(bais));
    } catch (JAXBException e) {
        throw new IllegalStateException("Error unmarshalling", e);
    }
}

From source file:jp.go.nict.langrid.client.soap.io.SoapResponseParser.java

private static <T> T nodeToType(XPathWorkspace w, Node node, Class<T> clazz, Converter converter)
        throws InstantiationException, IllegalAccessException, IllegalArgumentException,
        InvocationTargetException, ConversionException, DOMException, ParseException {
    if (clazz.isPrimitive()) {
        return converter.convert(resolveHref(w, node).getTextContent(), clazz);
    } else if (clazz.equals(String.class)) {
        return clazz.cast(resolveHref(w, node).getTextContent());
    } else if (clazz.equals(byte[].class)) {
        try {/*from  www. j a  v a  2  s.  c om*/
            return clazz.cast(Base64.decodeBase64(resolveHref(w, node).getTextContent().getBytes("ISO8859-1")));
        } catch (UnsupportedEncodingException e) {
            throw new RuntimeException(e);
        }
    } else if (clazz.equals(Calendar.class)) {
        Date date = fmt.get().parse(resolveHref(w, node).getTextContent());
        Calendar c = Calendar.getInstance();
        c.setTime(date);
        return clazz.cast(c);
    } else if (clazz.isArray()) {
        Class<?> ct = clazz.getComponentType();
        List<Object> elements = new ArrayList<Object>();
        node = resolveHref(w, node);
        for (Node child = node.getFirstChild(); child != null; child = child.getNextSibling()) {
            if (!(child instanceof Element))
                continue;
            elements.add(nodeToType(w, child, ct, converter));
        }
        return clazz.cast(elements.toArray((Object[]) Array.newInstance(ct, elements.size())));
    } else {
        T instance = clazz.newInstance();
        node = resolveHref(w, node);
        for (Node child = node.getFirstChild(); child != null; child = child.getNextSibling()) {
            if (!(child instanceof Element))
                continue;
            String nn = child.getLocalName();
            Method setter = ClassUtil.findSetter(clazz, nn);
            setter.invoke(instance,
                    nodeToType(w, resolveHref(w, child), setter.getParameterTypes()[0], converter));
        }
        return instance;
    }
}

From source file:io.fabric8.kubernetes.api.ParseTest.java

public static <T> T assertParseExampleFile(String fileName, Class<T> clazz) throws Exception {
    File exampleFile = new File(getKubernetesExamplesDir(), fileName);
    assertFileExists(exampleFile);/* w  ww .j a  v a2  s .  c  o m*/
    Object answer = OBJECT_MAPPER.readerFor(clazz).readValue(exampleFile);
    assertNotNull("Null returned while unmarshalling " + exampleFile, answer);
    LOG.info("Parsed: " + fileName + " as: " + answer);
    assertTrue("Is not an instance of " + clazz.getSimpleName() + " was: " + answer.getClass().getName(),
            clazz.isInstance(answer));
    return clazz.cast(answer);
}

From source file:io.coala.factory.ClassUtil.java

/**
 * @param serializable the {@link String} representation of the
 *            {@link Serializable} object
 * @return the deserialized {@link Object}
 * @throws CoalaException if value was not configured nor any default was
 *             set/*from w ww.ja  v  a 2 s . c  om*/
 */
public static <T> T deserialize(final String serializable, final Class<T> returnType) throws CoalaException {
    if (serializable == null || serializable.isEmpty())
        throw CoalaExceptionFactory.VALUE_NOT_SET.create("serializable");

    try (final ObjectInputStream in = new ObjectInputStream(
            new ByteArrayInputStream((byte[]) CODER.decode(serializable)))) {
        return returnType.cast(in.readObject());
    } catch (final Throwable e) {
        throw CoalaExceptionFactory.UNMARSHAL_FAILED.create(e, serializable, Object.class);
    }
}

From source file:io.github.moosbusch.lumpi.util.LumpiUtil.java

@SuppressWarnings("unchecked")
public static <T> T cast(Object obj, Class<?> type) {
    if ((obj != null) && (type != null)) {
        if (type.isPrimitive()) {
            Class<?> wrapperType = ClassUtils.primitiveToWrapper(type);

            if (ClassUtils.isAssignable(obj.getClass(), wrapperType)) {
                return (T) wrapperType.cast(obj);
            }/*w w w  . j a va 2  s.co m*/
        } else {
            if (ClassUtils.isAssignable(obj.getClass(), type)) {
                return (T) type.cast(obj);
            }
        }
    }

    return null;
}