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:net.nicholaswilliams.java.licensing.ObjectSerializer.java

/**
 * Deserializes an object of the specified type from the provided byte stream.
 *
 * @param expectedType The type that is expected to be retrieved from {@code byteStream} (must implement {@link Serializable})
 * @param byteStream The byte stream to retrieve the object from (it must contain exactly one object, of the exact type passed to {@code expectedType})
 * @return the requested unserialized object, presumably in the stream.
 * @throws ObjectTypeNotExpectedException If the object found in the stream does not match the type {@code expectedType} or if a {@link ClassNotFoundException} or {@link NoClassDefFoundError} occurs
 * @throws ObjectDeserializationException If an I/O exception occurs while deserializing the object from the stream
 *//*  www .j  a  va2s.c om*/
public final <T extends Serializable> T readObject(Class<T> expectedType, byte[] byteStream)
        throws ObjectDeserializationException {
    ByteArrayInputStream bytes = new ByteArrayInputStream(byteStream);
    ObjectInputStream stream = null;
    try {
        stream = new ObjectInputStream(bytes);
        Object allegedObject = stream.readObject();
        if (!expectedType.isInstance(allegedObject)) {
            throw new ObjectTypeNotExpectedException(expectedType.getName(),
                    allegedObject.getClass().getName());
        }

        return expectedType.cast(allegedObject);
    } catch (IOException e) {
        throw new ObjectDeserializationException(
                "An I/O error occurred while reading the object from the byte array.", e);
    } catch (ClassNotFoundException e) {
        throw new ObjectTypeNotExpectedException(expectedType.getName(), e.getMessage(), e);
    } catch (NoClassDefFoundError e) {
        throw new ObjectTypeNotExpectedException(expectedType.getName(), e.getMessage(), e);
    } finally {
        try {
            if (stream != null)
                stream.close();
        } catch (IOException ignore) {
        }
    }
}

From source file:edu.harvard.i2b2.fhir.FhirUtil.java

public static List<Object> getChildrenThruParPath(Resource r, String pathStr, MetaResourceDb db)
        throws NoSuchMethodException, SecurityException, IllegalAccessException, IllegalArgumentException,
        InvocationTargetException {

    List<Object> children = new ArrayList<Object>();
    List<Object> resolvedChildren = new ArrayList<Object>();
    List<Resource> s = db.getAll();

    logger.trace("got obj:" + r);
    Class c = FhirUtil.getResourceClass(r);

    String suffix = null;/*  w w w  . j a v a2 s.  c  o m*/
    String prefix = pathStr;
    logger.trace("pathStr:" + pathStr);

    if (pathStr.indexOf('.') > -1) {
        suffix = pathStr.substring(pathStr.indexOf('.') + 1);
        prefix = pathStr.substring(0, pathStr.indexOf('.'));
    }

    String methodName = prefix.substring(0, 1).toUpperCase() + prefix.subSequence(1, prefix.length());
    Method method = c.getMethod("get" + methodName, null);
    Object o = method.invoke(c.cast(r));

    if (List.class.isInstance(o)) {
        children.addAll((List<Object>) o);
    } else {
        children.add(o);
    }

    if (suffix == null) {
        return children;

    } else {

        for (Object child : children) {

            // if it is a reference resolve the reference
            if (Reference.class.isInstance(child)) {
                Reference rr = Reference.class.cast(child);
                logger.trace("gotc:" + child.getClass());
                Resource r1 = FhirUtil.findResourceById(rr.getReference().getValue(), s);
                resolvedChildren.add(getChildrenThruChain(r1, suffix, s));

            } else {
                resolvedChildren.add(getChildrenThruChain(r, suffix, s));
            }

        }
    }
    return resolvedChildren;
}

From source file:edu.harvard.i2b2.fhir.FhirUtil.java

public static List<Object> getChildrenThruChain(Resource r, String pathStr, List<Resource> s)
        // is dot separated path
        throws NoSuchMethodException, SecurityException, IllegalAccessException, IllegalArgumentException,
        InvocationTargetException {

    List<Object> children = new ArrayList<Object>();
    List<Object> resolvedChildren = new ArrayList<Object>();
    logger.trace("got obj:" + r);
    Class c = FhirUtil.getResourceClass(r);

    String suffix = null;/* w w w. ja  v  a  2 s.c om*/
    String prefix = pathStr;
    logger.trace("pathStr:" + pathStr);

    if (pathStr.indexOf('.') > -1) {
        suffix = pathStr.substring(pathStr.indexOf('.') + 1);
        prefix = pathStr.substring(0, pathStr.indexOf('.'));
    }

    String methodName = prefix.substring(0, 1).toUpperCase() + prefix.subSequence(1, prefix.length());
    Method method = c.getMethod("get" + methodName, null);
    Object o = method.invoke(c.cast(r));

    if (List.class.isInstance(o)) {
        children.addAll((List<Object>) o);
    } else {
        children.add(o);
    }

    if (suffix == null) {
        return children;

    } else {

        for (Object child : children) {
            if (Reference.class.isInstance(child)) {
                Reference rr = Reference.class.cast(child);
                logger.trace("gotc:" + child.getClass());

                /*
                 * try { logger.trace("seek:" + JAXBUtil.toXml(rr));
                 * logger.trace("seek:" + rr.getReference().getValue()); }
                 * catch (JAXBException e) { // TODO Auto-generated catch
                 * block e.printStackTrace(); }
                 */

                Resource r1 = FhirUtil.findResourceById(rr.getReference().getValue(), s);
                resolvedChildren.add(getChildrenThruChain(r1, suffix, s));

            } else {
                resolvedChildren.add(getChildrenThruChain(r, suffix, s));
            }

        }
    }
    return resolvedChildren;
}

From source file:org.exoplatform.container.spring.SpringContainer.java

private <T> T getInstanceOfType(final Class<T> componentType) {
    T result;//from  w w w  .j a va 2s .c o  m
    PrivilegedAction<T> action = new PrivilegedAction<T>() {
        public T run() {
            String name = classToBeanName(componentType);
            if (ctx.containsBean(name) && componentType.isAssignableFrom(ctx.getType(name))) {
                return componentType.cast(ctx.getBean(name));
            }
            String[] names = ctx.getBeanNamesForType(componentType);
            if (names != null && names.length > 0) {
                return componentType.cast(ctx.getBean(names[0]));
            }
            return null;
        }
    };
    result = SecurityHelper.doPrivilegedAction(action);
    return result;
}

From source file:org.openvpms.component.business.dao.hibernate.im.common.Context.java

/**
 * Retrieves a data object given its reference.
 *
 * @param reference the reference/*from ww  w.j  a va  2s . c om*/
 * @param type      the data object type
 * @param impl      the data object implementation type
 * @return the corresponding object, or <tt>null</tt> if none is found
 */
public <T extends IMObjectDO, Impl extends IMObjectDOImpl> T get(IMObjectReference reference, Class<T> type,
        Class<Impl> impl) {
    Object result = session.load(impl, reference.getId());
    return type.cast(result);
}

From source file:org.exoplatform.container.spring.SpringContainer.java

private <T> ComponentAdapter<T> createComponentAdapter(final Class<T> type, final String name) {
    return new AbstractComponentAdapter<T>(type, type) {
        /**//from w  w  w.  ja v  a2s.  com
         * The serial UID
         */
        private static final long serialVersionUID = -4625398501079851570L;

        public T getComponentInstance() throws ContainerException {
            return type.cast(ctx.getBean(name));
        }

        public boolean isSingleton() {
            return ctx.isSingleton(name);
        }
    };
}

From source file:fr.gael.dhus.util.http.DownloadableProduct.java

@Override
public <T> T getImpl(Class<? extends T> cl) {
    if (InputStream.class.isAssignableFrom(cl)) {
        try {/*from  w  w  w  . jav  a 2s .c  o  m*/
            Pipe pipe = Pipe.open();
            DownloadTask dltask = new DownloadTask(pipe);
            downloadThread = new Thread(dltask, "Product Download");
            downloadThread.start();

            InputStream is = Channels.newInputStream(pipe.source());
            return cl.cast(is);
        } catch (IOException ex) {
            LOGGER.error("could not create pipe", ex);
        }
    }
    return null;
}

From source file:com.netflix.spinnaker.clouddriver.aws.security.sdkclient.ProxyHandlerBuilder.java

public <T extends AwsClientBuilder<T, U>, U> U getProxyHandler(Class<U> interfaceKlazz, Class<T> impl,
        NetflixAmazonCredentials amazonCredentials, String region, boolean skipEdda) {
    requireNonNull(amazonCredentials, "Credentials cannot be null");
    try {/*from w  w w  . j  a va 2 s  . c om*/
        U delegate = awsSdkClientSupplier.getClient(impl, interfaceKlazz, amazonCredentials.getName(),
                amazonCredentials.getCredentialsProvider(), region);
        if (skipEdda || !amazonCredentials.getEddaEnabled()
                || eddaTimeoutConfig.getDisabledRegions().contains(region)) {
            return delegate;
        }
        return interfaceKlazz.cast(Proxy.newProxyInstance(getClass().getClassLoader(),
                new Class[] { interfaceKlazz },
                getInvocationHandler(delegate, interfaceKlazz.getSimpleName(), region, amazonCredentials)));
    } catch (RuntimeException re) {
        throw re;
    } catch (Exception e) {
        throw new RuntimeException("Instantiation of client implementation failed!", e);
    }
}

From source file:eu.udig.style.advanced.utils.Utilities.java

/**
 * Checks if a string is a number (currently Double, Float, Integer).
 * //from  w w w.  j  av  a2 s .  c  o  m
 * @param value the string to check. 
 * @param adaptee the class to check against. If null, the more permissive {@link Double} will be used.
 * @return the number or null, if the parsing fails.
 */
@SuppressWarnings("unchecked")
public static <T extends Number> T isNumber(String value, Class<T> adaptee) {
    if (value == null) {
        return null;
    }
    if (adaptee == null) {
        adaptee = (Class<T>) Double.class;
    }
    if (adaptee.isAssignableFrom(Double.class)) {
        try {
            Double parsed = Double.parseDouble(value);
            return adaptee.cast(parsed);
        } catch (Exception e) {
            return null;
        }
    } else if (adaptee.isAssignableFrom(Float.class)) {
        try {
            Float parsed = Float.parseFloat(value);
            return adaptee.cast(parsed);
        } catch (Exception e) {
            return null;
        }
    } else if (adaptee.isAssignableFrom(Integer.class)) {
        try {
            Integer parsed = Integer.parseInt(value);
            return adaptee.cast(parsed);
        } catch (Exception e) {
            // still try the double
            Double number = isNumber(value, Double.class);
            if (number != null) {
                return adaptee.cast(number.intValue());
            }
            return null;
        }
    } else {
        throw new IllegalArgumentException();
    }
}

From source file:edu.harvard.i2b2.fhir.FhirUtil.java

public static Object getChild(Resource r, String pathStr)
        // is dot separated path
        throws NoSuchMethodException, SecurityException, IllegalAccessException, IllegalArgumentException,
        InvocationTargetException {
    Class c = FhirUtil.getResourceClass(r);
    String returnStr = null;/*from ww w.j a  va  2s  .  co  m*/
    String suffix = null;
    String prefix = pathStr;
    logger.trace("pathStr:" + pathStr);
    if (pathStr.indexOf('.') > -1) {
        suffix = pathStr.substring(pathStr.indexOf('.') + 1);
        prefix = pathStr.substring(0, pathStr.indexOf('.'));
    }
    String methodName = prefix.substring(0, 1).toUpperCase() + prefix.subSequence(1, prefix.length());
    Method method = c.getMethod("get" + methodName, null);
    if (suffix == null) {
        Object o = method.invoke(c.cast(r));
        if (Reference.class.isInstance(o)) {
            return o;
        } else {
            return o;
        }
    } else {
        return getChild(r, suffix);
    }

}