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:io.github.restdocsext.jersey.JerseyRequestConverter.java

/**
 * Extract an entity from the {@code ClientRequestContext} and return it in the form of the
 * type specified as the {@code returnType} argument.
 *
 * @param <T> The type of entity to return.
 * @param request the {@code ClientRequest} for the request.
 * @param returnType the return type of the entity extraction.
 * @param entityType the entity type./* w w  w .j  a v a 2 s.  co m*/
 * @return the entity in the form if the type specifies as the {@code entityType} argument.
 */
private static <T, U> T extractEntity(ClientRequest request, Class<T> returnType, Class<U> entityType) {
    try {
        final MessageBodyWorkers workers = request.getWorkers();
        final Object entity = request.getEntity();
        final MultivaluedMap<String, Object> headers = request.getHeaders();
        final Type type = request.getEntityType() == null ? entityType : request.getEntityType();

        MediaType mediaType = request.getMediaType();

        final ByteArrayOutputStream entityOut = new ByteArrayOutputStream();
        final MessageBodyWriter<U> writer = findWriter(workers, entityType, type, new Annotation[0], mediaType);
        if (writer == null) {
            throw new IllegalStateException(
                    "No MessageBodyWriter found for mediatype " + mediaType + " and java type " + entityType);
        }

        writer.writeTo(entityType.cast(entity), entityType, type, new Annotation[0], mediaType, headers,
                entityOut);

        final ByteArrayInputStream entityIn = new ByteArrayInputStream(entityOut.toByteArray());
        final MessageBodyReader<T> reader = workers.getMessageBodyReader(returnType, null, new Annotation[0],
                mediaType);
        if (reader == null) {
            throw new IllegalStateException(
                    "No MessageBodyReader found for mediatype " + mediaType + " and java type " + returnType);
        }

        if (isMultiPartRequest(request)) {
            // If we don't do this, the boundary is not included
            // So we add the boundary ourselves.
            final String contentType = (String) headers.getFirst(HttpHeaders.CONTENT_TYPE);
            final String[] split = contentType.split(";");
            final Map<String, String> parameters = new HashMap<>();
            for (int i = 1; i < split.length; i++) {
                String[] paramPair = split[i].split("=");
                if (paramPair.length == 2) {
                    parameters.put(paramPair[0].trim(), paramPair[1].trim());
                }
            }
            if (!parameters.containsKey("boundary")) {
                throw new IllegalStateException(String
                        .format("Content-Type for multipart request does not have boundary: %s", contentType));
            }
            mediaType = new MediaType(mediaType.getType(), mediaType.getSubtype(), parameters);
        }

        return (T) reader.readFrom(returnType, returnType, new Annotation[0], mediaType,
                objectMapToStringMap(headers), entityIn);
    } catch (IOException ex) {
        throw new RuntimeException("Could not extract entity.", ex);
    }
}

From source file:hudson.Util.java

/**
 * Create a sub-list by only picking up instances of the specified type.
 *///from   w  w  w.  j a v a2s  .c om
public static <T> List<T> createSubList(Collection<?> source, Class<T> type) {
    List<T> r = new ArrayList<T>();
    for (Object item : source) {
        if (type.isInstance(item))
            r.add(type.cast(item));
    }
    return r;
}

From source file:com.orchestra.portale.controller.PoiViewController.java

@RequestMapping(value = "/getPoi", params = "id")
public ModelAndView getPoi(@RequestParam(value = "id") String id) {

    //Creo la view che sar mostrata all'utente
    ModelAndView model = new ModelAndView("infopoi");
    ModelAndView error = new ModelAndView("errorViewPoi");
    CompletePOI poi = pm.getCompletePoiById(id);
    //aggiungo il poi al model
    model.addObject("poi", poi);
    try {/*ww w . j a va  2  s  . com*/
        //ciclo sulle componenti del poi
        for (AbstractPoiComponent comp : poi.getComponents()) {

            //associazione delle componenti al model tramite lo slug
            String slug = comp.slug();
            int index = slug.lastIndexOf(".");
            String cname = slug.substring(index + 1).replace("Component", "").toLowerCase();

            Class c = Class.forName(slug);
            model.addObject(cname, c.cast(comp));

        }
    } catch (Exception e) {
        return error;
    }
    return model;
}

From source file:com.twosigma.beakerx.kernel.EvaluatorParameters.java

public <T> Optional<T> getParam(String key, Class<T> clazz) {
    if (params.containsKey(key)) {
        return Optional.of(clazz.cast(params.get(key)));
    }/*from   w w w .j ava 2  s. com*/
    return Optional.empty();
}

From source file:org.openmrs.module.webservices.rest.web.api.impl.RestHelperServiceImpl.java

/**
 * @see org.openmrs.module.webservices.rest.web.api.RestHelperService#getConceptMapByUuid(java.lang.String)
 *//*from w  ww  . j  ava 2  s  .com*/
@Override
@Transactional(readOnly = true)
public <T> T getObjectByUuid(Class<? extends T> type, String uuid) {
    return type.cast(getSession().createCriteria(type).add(Restrictions.eq("uuid", uuid)).uniqueResult());
}

From source file:com.palantir.ptoss.util.Reflections.java

/**
 * Returns a {@link Function} that will read values from the named field from a passed object.
 * @param klass type to read values from
 * @param returnType return type of read field
 * @param getter name of the field/*from  w w w.  j  ava  2 s .  c o  m*/
 * @return a {@link Function} object that, when applied to an instance of <code>klass</code>, returns the
 * of type <code>returnType</code> that resides in field <code>getter</code>
 */
public static <F, T> Function<F, T> getterFunction(final Class<F> klass, final Class<T> returnType,
        String getter) {
    try {
        BeanInfo beanInfo = Introspector.getBeanInfo(klass);
        PropertyDescriptor[] props = beanInfo.getPropertyDescriptors();
        Method method = null;
        for (PropertyDescriptor descriptor : props) {
            if (descriptor.getName().equals(getter)) {
                method = descriptor.getReadMethod();
                break;
            }
        }
        if (method == null) {
            throw new IllegalStateException();
        }
        final Method readMethod = method;
        return new Function<F, T>() {
            public T apply(F from) {
                try {
                    return returnType.cast(readMethod.invoke(from));
                } catch (Exception e) {
                    Throwables.throwUncheckedException(e);
                    return null;
                }
            }
        };
    } catch (IntrospectionException e) {
        Throwables.throwUncheckedException(e);
        return null;
    }
}

From source file:org.openmrs.module.webservices.rest.web.api.impl.RestHelperServiceImpl.java

/**
 * @see org.openmrs.module.webservices.rest.web.api.RestHelperService#getObjectById(java.lang.Class,
 *      java.io.Serializable)/*  w  ww  .  ja v a  2s  .  c  o  m*/
 */
@Override
public <T> T getObjectById(Class<? extends T> type, Serializable id) {
    return type.cast(getSession().get(type, id));
}

From source file:com.gzj.tulip.load.context.RoseAppContext.java

/**
 *  Bean, ? {@link ApplicationContext}  Bean.
 * //from w w  w  . jav  a2  s.  c om
 * @param beanType - Bean 
 * 
 * @throws BeansException
 */
public <T> T getBean(Class<T> beanType) throws BeansException {
    return beanType.cast(BeanFactoryUtils.beanOfTypeIncludingAncestors(this, beanType));
}

From source file:com.startechup.tools.ModelParser.java

/**
 * Gets the values from the {@link JSONObject JSONObjects}/response returned from an api call
 * request and assign it to the field inside the class that will contain the parsed values.
 *
 * @param classModel The class type that will contain the parse value.
 * @param jsonObject The API response object.
 * @return Returns a generic class containing the values from the json, null if exception occurs.
 *//* w ww  .  j ava  2  s.  co  m*/
public static <T> T parse(Class<T> classModel, JSONObject jsonObject) {
    Object object = getNewInstance(classModel);

    if (object != null) {
        // TODO this solution is much accurate but not flexible when using a 3rd party library
        // for object model creation like squidb from yahoo, annotation should be added to the class method
        // and we cannot do that on squidb generated Class model.
        for (Method method : classModel.getDeclaredMethods()) {
            if (method.isAnnotationPresent(SetterSpec.class)) {
                SetterSpec methodLinker = method.getAnnotation(SetterSpec.class);
                String jsonKey = methodLinker.jsonKey();

                initMethodInvocation(method, object, jsonKey, jsonObject);
            }
        }
        return classModel.cast(object);
    } else {
        return null;
    }
}

From source file:org.jrb.commons.web.AbstractResponse.java

@Override
public <T> T getHeader(final String key, final Class<T> headerClass) {
    return headerClass.cast(headers.get(key));
}