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.atlassian.jira.ComponentManager.java

/**
 * Looks up a service from the OsgiContainerManager. This method should be avoided since it creates and closes a
 * new ServiceTracker each time it is called.
 *
 * @see JiraOsgiContainerManager#getOsgiComponentOfType(Class)
 *//*from  w  w w.ja va2  s  . c  o m*/
private static <T> T getOsgiComponentOfType(@Nonnull Class<T> clazz,
        @Nonnull OsgiContainerManager osgiContainerManager) {
    if (log.isDebugEnabled()) {
        log.debug(String.format(
                "Using slow getOsgiComponentOfType() to get '%s'. COMPONENT MANAGER. Y U NO JiraOsgiContainerManager!?",
                clazz.getName()), new Throwable());
    }

    ServiceTracker serviceTracker = osgiContainerManager.getServiceTracker(clazz.getName());
    if (serviceTracker != null) {
        try {
            return clazz.cast(serviceTracker.getService());
        } finally {
            serviceTracker.close();
        }
    }

    return null;
}

From source file:net.di2e.ecdr.commons.CDRMetacard.java

protected <T> T getAttributeValue(Attribute attribute, Class<T> returnType) {
    Serializable data = attribute.getValue();

    if (returnType.isAssignableFrom(data.getClass())) {
        return returnType.cast(data);
    } else {/*w  ww  .ja v  a2 s. c  om*/
        if (LOGGER.isDebugEnabled()) {
            LOGGER.trace(data.getClass().toString() + " can not be assigned to " + returnType.toString());
        }
    }
    return null;
}

From source file:org.killbill.billing.client.KillBillHttpClient.java

private <T> T deserializeResponse(final Response response, final Class<T> clazz)
        throws KillBillClientException {
    // No deserialization required
    if (Response.class.isAssignableFrom(clazz)) {
        return clazz.cast(response);
    }/*  w  w w  .  j av a  2  s. co m*/

    final T result = unmarshalResponse(response, clazz);
    if (KillBillObjects.class.isAssignableFrom(clazz)) {
        final KillBillObjects objects = ((KillBillObjects) result);
        final String paginationCurrentOffset = response.getHeader(JaxrsResource.HDR_PAGINATION_CURRENT_OFFSET);
        if (paginationCurrentOffset != null) {
            objects.setPaginationCurrentOffset(Integer.parseInt(paginationCurrentOffset));
        }
        final String paginationNextOffset = response.getHeader(JaxrsResource.HDR_PAGINATION_NEXT_OFFSET);
        if (paginationNextOffset != null) {
            objects.setPaginationNextOffset(Integer.parseInt(paginationNextOffset));
        }
        final String paginationTotalNbRecords = response
                .getHeader(JaxrsResource.HDR_PAGINATION_TOTAL_NB_RECORDS);
        if (paginationTotalNbRecords != null) {
            objects.setPaginationTotalNbRecords(Integer.parseInt(paginationTotalNbRecords));
        }
        final String paginationMaxNbRecords = response.getHeader(JaxrsResource.HDR_PAGINATION_MAX_NB_RECORDS);
        if (paginationMaxNbRecords != null) {
            objects.setPaginationMaxNbRecords(Integer.parseInt(paginationMaxNbRecords));
        }
        objects.setPaginationNextPageUri(response.getHeader(JaxrsResource.HDR_PAGINATION_NEXT_PAGE_URI));
        objects.setKillBillHttpClient(this);
    }

    return result;
}

From source file:net.smart_json_database.JSONDatabase.java

public int insert(Object object, Class<?> clazz) throws JsonProcessingException, IOException, JSONException {
    final ObjectMapper objectMapper = new ObjectMapper();

    String jsonString = objectMapper.writeValueAsString(clazz.cast(object));
    JSONEntity entity = JSONEntity.ParseFromString(jsonString);
    return insert(entity);
}

From source file:org.jutility.common.datatype.tuple.TupleBase.java

/**
 * Creates a new instance of the {@code TupleBase} class with the provided
 * type and values./*from  w w w . j a  v a  2  s .  c o  m*/
 *
 * @param components
 *            The components of this tuple.
 * @param type
 *            The type of this tuple.
 * @param serialization
 *            whether or not the constructor is invoked during
 *            serialization.
 */
protected TupleBase(final T[] components, final Class<? extends T> type, final boolean serialization) {

    if ((components == null) && !serialization) {

        TupleBase.LOG.error("Cannot create a tuple without components!");
        throw new IllegalArgumentException("Cannot create a tuple without components!");
    }
    if ((type == null) && !serialization) {

        TupleBase.LOG.error("Cannot create a tuple without a type!");
        throw new IllegalArgumentException("Cannot create a tuple without a type!");
    }

    this.components = new LinkedList<T>();

    if ((components != null) && (type != null)) {

        for (final Object component : components) {

            if (type.isAssignableFrom(component.getClass())) {

                this.components.add(type.cast(component));
            } else {

                TupleBase.LOG.error("Cannot assign a value of type " + component.getClass()
                        + " to a Tuple of type " + type + "!");
                throw new IllegalArgumentException("Cannot assign a value of type " + component.getClass()
                        + " to a Tuple of type " + type + "!");
            }
        }
    }

    this.type = type;
}

From source file:org.cleverbus.core.AbstractOperationRouteTest.java

/**
 * Sends the test request to the IN route (as if it was received via Spring WS).
 *
 * @param correlationID   the new message correlation ID
 * @param msgTimestamp    the new message timestamp
 * @param requestXML      the request payload (XML) to send
 * @param messageVerifier the processor that can verify the {@link Message} created in the DB
 * @param responseClass   the response class to parse response XML as
 * @return the response parsed from XML as the specified responseClass
 * @throws Exception//from  w ww  .java2  s.  c om
 * @throws AssertionError if the message state doesn't match the specified state
 */
protected <T> T sendAsyncInMessage(String correlationID, DateTime msgTimestamp, String requestXML,
        MessageProcessor messageVerifier, Class<T> responseClass) throws Exception {
    Exchange result = sendAsyncInMessage(correlationID, msgTimestamp, requestXML);
    Exception exception = result.getException();
    if (exception != null) {
        throw exception;
    }

    verifyMessage(getSourceSystem(), correlationID, messageVerifier);
    String responseXML = result.getOut().getMandatoryBody(String.class);
    if (responseClass.isAssignableFrom(String.class)) {
        return responseClass.cast(responseXML);
    }
    return unmarshalFragment(responseXML, responseClass);
}

From source file:com.mac.tarchan.desktop.event.EventQuery.java

/**
 * ???????//from w  ww  . j  a v a  2s  . c  om
 * 
 * @param type ???
 * @return ??
 */
public <T extends Component> T first(Class<T> type) {
    Iterator<Component> it = list.iterator();
    return it.hasNext() ? type.cast(it.next()) : null;
}

From source file:com.taobao.adfs.database.tdhsocket.client.response.TDHSResutSet.java

public <T> T unwrap(Class<T> iface) throws SQLException {
    try {/*from   w  ww. j av a 2s . co  m*/
        // This works for classes that aren't actually wrapping
        // anything
        return iface.cast(this);
    } catch (ClassCastException cce) {
        throw new SQLException(cce);
    }
}

From source file:com.jsen.core.misc.MimeContentRegistryBase.java

/**
 * Constructs MIME content factory from a given class and constructor arguments.
 * //from   w ww.j av  a  2 s. c o m
 * @param factoryClass MIME content factory class of which should be constructed the instance.
 * @param args Constructor arguments for factory.
 * @return Constructed MIME content factory on success, otherwise null.
 */
protected MimeContentFactory instantizeMimeContentFactory(Class<? extends MimeContentFactory> factoryClass,
        Object... args) {
    MimeContentFactory mimeContentFactory = null;

    try {
        /*List<Class<?>> constructorClassesList = new ArrayList<Class<?>>();
                
        for (Object arg : args) {
           constructorClassesList.add(arg.getClass());
        }
                
        Class<?> constructorClasses[] = constructorClassesList.toArray(new Class<?>[constructorClassesList.size()]);
                
        Constructor<? extends MimeContentFactoryBase<?>> mimeContentFactoryConstructor = factoryClass.getConstructor(constructorClasses);
        mimeContentFactory = mimeContentFactoryConstructor.newInstance(args);*/

        Object newInstance = ConstructorUtils.invokeConstructor(factoryClass, args);
        mimeContentFactory = factoryClass.cast(newInstance);

    } catch (Exception e) {
        e.printStackTrace();
    }

    return mimeContentFactory;
}

From source file:com.mondora.chargify.controller.ChargifyAdapter.java

protected Object parse(Class clazz, InputStream inputStream) throws ChargifyException {
    byte[] in = null;
    try {/*from   w  w w. j  a v a  2s .  c o m*/
        JAXBContext context = JAXBContext.newInstance(clazz);
        Unmarshaller unmarshaller = context.createUnmarshaller();
        unmarshaller.setSchema(null);
        if (logger.isTraceEnabled()) {
            try {
                in = readByteStream(inputStream);
                logger.trace("Response input " + new String(in));

                inputStream = new ByteArrayInputStream(in);
            } catch (IOException e) {
            }
        }
        Object xmlObject = clazz.cast(unmarshaller.unmarshal(inputStream));
        return xmlObject;
    } catch (JAXBException e) {
        if (logger.isTraceEnabled())
            logger.trace(e.getMessage(), e);
        if (logger.isInfoEnabled())
            logger.info(e.getMessage());
        throw new ChargifyException("Unparsable Entity " + new String(in));
    }
}