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:org.synyx.hades.util.ClassUtils.java

/**
 * Returns whether the given {@link EntityManager} is of the given type.
 * /*  w  w  w .ja  va2s.com*/
 * @param em
 * @param type the fully qualified expected {@link EntityManager} type.
 * @return
 */
@SuppressWarnings("unchecked")
public static boolean isEntityManagerOfType(EntityManager em, String type) {

    try {

        Class<? extends EntityManager> emType = (Class<? extends EntityManager>) Class.forName(type);

        emType.cast(em);

        return true;

    } catch (ClassNotFoundException e) {
        return false;
    } catch (ClassCastException e) {
        return false;
    } catch (NoClassDefFoundError e) {
        return false;
    }
}

From source file:de.anhquan.config4j.ConfigFactory.java

public static <T extends Config> T getConfig(Class<T> configType) {
    T configInst = (T) instances.get(configType);
    if (configInst != null) {
        return configInst;
    }/*from  w ww. j  av  a2  s.  com*/

    ClassLoader classLoader = configType.getClassLoader();
    Class[] classes = { configType };
    InvocationHandler handler = new ConfigHandler(configType);
    Object proxy = Proxy.newProxyInstance(classLoader, classes, handler);
    configInst = configType.cast(proxy);
    instances.put(configType, configInst);

    return configInst;
}

From source file:com.openappengine.utility.ObjectConverter.java

/**
 * Convert the given object value to the given class.
 * @param from The object value to be converted.
 * @param to The type class which the given object should be converted to.
 * @return The converted object value.//from   w w  w.j  a  va 2 s .  co m
 * @throws NullPointerException If 'to' is null.
 * @throws UnsupportedOperationException If no suitable converter can be found.
 * @throws RuntimeException If conversion failed somehow. This can be caused by at least
 * an ExceptionInInitializerError, IllegalAccessException or InvocationTargetException.
 */
public static <T> T convert(Object from, Class<T> to) {

    // Null is just null.
    if (from == null) {
        return null;
    }

    // Can we cast? Then just do it.
    if (to.isAssignableFrom(from.getClass())) {
        return to.cast(from);
    }

    // Lookup the suitable converter.
    String converterId = from.getClass().getName() + "_" + to.getName();
    Method converter = CONVERTERS.get(converterId);
    if (converter == null) {
        throw new ObjectConverterException("Cannot convert from " + from.getClass().getName() + " to "
                + to.getName() + ". Requested converter does not exist.");
    }

    // Convert the value.
    try {
        return to.cast(converter.invoke(to, from));
    } catch (Exception e) {
        throw new ObjectConverterException("Cannot convert from " + from.getClass().getName() + " to "
                + to.getName() + ". Conversion failed with " + e.getMessage(), e);
    }
}

From source file:Main.java

/**
 * Tries to initialize fragment of type clazz by one of methods:
 * init(Bundle), init()./*from   ww w .  j  av a  2s.co m*/
 *
 * @param clazz type of fragment to initialize
 * @param data data to initialize fragment with
 * @param <T> child of Fragment class
 * @return initialized fragment or null
 */
private static <T extends Fragment> T initFragment(Class<T> clazz, Bundle data) {

    final String INIT = "newInstance";

    try {
        Method init;
        Object fragment;

        if (data != null) {
            init = clazz.getMethod(INIT, Bundle.class);
            fragment = init.invoke(null, data);

        } else {
            init = clazz.getMethod(INIT);
            fragment = init.invoke(null);
        }
        return clazz.cast(fragment);

    } catch (NoSuchMethodException | IllegalAccessException | IllegalArgumentException
            | InvocationTargetException | ClassCastException e) {
        e.printStackTrace();
    }
    return null;
}

From source file:com.vmware.admiral.compute.container.volume.VolumeUtil.java

private static <T extends ResourceState> Map<String, T> filterDescriptions(Class<T> clazz,
        Collection<ComponentDescription> componentDescriptions) {

    return componentDescriptions.stream().filter(cd -> clazz.isInstance(cd.getServiceDocument()))
            .map(cd -> clazz.cast(cd.getServiceDocument())).collect(Collectors.toMap(c -> c.name, c -> c));
}

From source file:net.ripe.rpki.commons.crypto.util.Asn1Util.java

/**
 * Checks if <code>value</code> is an instance of the
 * <code>expectedClass</code>.
 *
 * @throws IllegalArgumentException the instance is null or not an instance of the expected
 *                                  class.
 *//*ww w  .ja  v a2s  .c o  m*/
public static <T extends ASN1Encodable> T expect(ASN1Encodable value, Class<? extends T> expectedClass) {
    Validate.notNull(value, expectedClass.getSimpleName() + " expected, got null");
    Validate.isTrue(expectedClass.isInstance(value), expectedClass.getSimpleName() + " expected, got "
            + value.getClass().getSimpleName() + " with value: " + value);
    return expectedClass.cast(value);
}

From source file:Main.java

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

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

    return (T) xmlObject;
}

From source file:com.thoughtworks.go.config.BasicEnvironmentConfig.java

private static <T> T as(Class<T> clazz, Object o) {
    if (clazz.isInstance(o)) {
        return clazz.cast(o);
    }//from   w  w w  .ja v  a 2 s  . c  om
    return null;
}

From source file:com.cloudera.sqoop.shims.ShimLoader.java

/**
 * Check the current classloader to see if it can load the prescribed
 * class name as an instance of 'xface'. If so, create an instance of
 * the class and return it.//from   www. j a  v  a  2 s . c o m
 * @param className the shim class to attempt to instantiate.
 * @param xface the interface it must implement.
 * @return an instance of className.
 */
private static <T> T getShimInstance(String className, Class<T> xface)
        throws ClassNotFoundException, InstantiationException, IllegalAccessException {
    ClassLoader cl = Thread.currentThread().getContextClassLoader();
    Class clazz = Class.forName(className, true, cl);
    return xface.cast(clazz.newInstance());
}

From source file:com.music.tools.ScaleTester.java

private static <T extends Number> T getArgument(String[] args, int i, T defaultValue, Class<T> resultClass) {
    if (args.length > i) {
        return resultClass.cast(Double.parseDouble(args[i]));
    } else {//from  w w w  . j  a  v a 2 s. c o  m
        return defaultValue;
    }
}