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:de.decoit.simu.cbor.ifmap.deserializer.MetadataDeserializerManager.java

/**
 * Deserialize an object of the specified class from the specified data items.
 * The attributes and nested tags arrays may be empty but never null.
 *
 * @param <T> Type of the object to be deserialized, must be a subclass of {@link AbstractMetadata}
 * @param namespace CBOR data item representing the element namespace
 * @param cborName CBOR data item representing the element name
 * @param attributes CBOR array data item containing the element's attributes
 * @param nestedDataItem CBOR data item containing the element's nested tags or value
 * @param metadataType Type of the object to be deserialized
 * @return The deserialized object// www. jav  a2s  . c  o m
 * @throws CBORDeserializationException if deserialization failed
 */
public static <T extends AbstractMetadata> T deserialize(final DataItem namespace, final DataItem cborName,
        final Array attributes, final DataItem nestedDataItem, final Class<T> metadataType)
        throws CBORDeserializationException {
    if (namespace == null) {
        throw new IllegalArgumentException("Namespace must not be null");
    }

    if (cborName == null) {
        throw new IllegalArgumentException("CBOR name must not be null");
    }

    if (attributes == null) {
        throw new IllegalArgumentException("Attributes array must not be null");
    }

    if (nestedDataItem == null) {
        throw new IllegalArgumentException("Nested tags array must not be null");
    }

    if (metadataType == null) {
        throw new IllegalArgumentException("Target metadata type must not be null");
    }

    try {
        // If default deserializers were not registered yet, do so
        if (!initialized) {
            init();
        }

        // Check if a deserializer for this type was registered
        if (hasVendorDeserializer(metadataType)) {
            DictionarySimpleElement elementEntry = getTopLevelElement(namespace, cborName);

            return metadataType.cast(registeredDeserializers.get(metadataType).deserialize(attributes,
                    nestedDataItem, elementEntry));
        }

        // If no deserializer was found, fail with exception
        throw new UnsupportedOperationException("Cannot deserialize class: " + metadataType.getCanonicalName());
    } catch (CBORDeserializationException ex) {
        throw ex;
    } catch (Exception ex) {
        throw new CBORDeserializationException("Could not cast deserialization result to target class", ex);
    }
}

From source file:org.spring.data.gemfire.cache.JsonToPdxToObjectDataAccessIntegrationTest.java

protected <T> T fromPdx(Object pdxInstance, Class<T> toType) {
    try {//from w w w. jav  a2 s .  c  o m
        if (pdxInstance == null) {
            return null;
        } else if (toType.isInstance(pdxInstance)) {
            return toType.cast(pdxInstance);
        } else if (pdxInstance instanceof PdxInstance) {
            return new ObjectMapper().readValue(JSONFormatter.toJSON(((PdxInstance) pdxInstance)), toType);
        } else {
            throw new IllegalArgumentException(String.format(
                    "Expected object of type PdxInstance; but was (%1$s)", pdxInstance.getClass().getName()));
        }
    } catch (IOException e) {
        throw new RuntimeException(String.format("Failed to convert PDX to object of type (%1$s)", toType), e);
    }
}

From source file:com.maxpowered.amazon.advertising.api.SignedRequestsHelper.java

public <T> T unmarshal(final InputStream responseStream, final Class<T> clazz)
        throws JAXBException, XMLStreamException, IOException {
    T response;//from   www. j  av a  2  s . co  m
    try {
        response = clazz.cast(unmarshaller.unmarshal(responseStream));
    } finally {
        responseStream.close();
    }

    return response;
}

From source file:net.refractions.udig.catalog.internal.shp.ShpGeoResourceImpl.java

public <T> T resolve(Class<T> adaptee, IProgressMonitor monitor) throws IOException {
    if (adaptee == null) {
        return null;
    }//from ww w.  ja v  a2s.  co  m
    if (adaptee.isAssignableFrom(IGeoResource.class)) {
        return adaptee.cast(this);
    }
    if (adaptee.isAssignableFrom(IGeoResourceInfo.class)) {
        return adaptee.cast(createInfo(monitor));
    }
    if (adaptee.isAssignableFrom(FeatureStore.class)) {
        FeatureSource<SimpleFeatureType, SimpleFeature> fs = featureSource(monitor);
        if (fs instanceof FeatureStore) {
            return adaptee.cast(fs);
        }
    }
    if (adaptee.isAssignableFrom(FeatureSource.class)) {
        return adaptee.cast(featureSource(monitor));
    }
    if (adaptee.isAssignableFrom(IndexedShapefileDataStore.class)) {
        return adaptee.cast(parent.getDS(monitor));
    }
    if (adaptee.isAssignableFrom(Style.class)) {
        Style style = style(monitor);
        if (style != null) {
            return adaptee.cast(style(monitor));
        }
        // proceed to ask the super class, someone may
        // of written an IResolveAdapaterFactory providing us
        // with a style ...
    }
    return super.resolve(adaptee, monitor);
}

From source file:com.github.rinde.rinsim.core.model.road.GraphRoadModel.java

@Override
@Nonnull
public <U> U get(Class<U> type) {
    return type.cast(self);
}

From source file:grails.config.GrailsConfig.java

/**
 * Utility method for retrieving a configuration value and performs type checking
 * (i.e. logs a verbose WARN message on type mismatch).
 *
 * @param key the flattened key// w w  w.java  2s.  co m
 * @param type the required type
 * @param <T> the type parameter
 * @return the value retrieved by ConfigurationHolder.flatConfig
 */
public <T> T get(String key, Class<T> type) {
    Object o = get(key);
    if (o != null) {
        if (!type.isAssignableFrom(o.getClass())) {
            LOG.warn(String.format("Configuration type mismatch for configuration value %s (%s)", key,
                    type.getName()));
            return null;
        }
        return type.cast(o);
    }
    return null;
}

From source file:com.otiliouine.configurablefactory.ConfigurableFactory.java

/**
 * Creates an instance of the implementation class mapped to <b>interfazz</b>
 * //w  w w  .  j a v  a 2  s  .c o m
 * @param interfazz the Interface or class which represents the abstraction of instance types
 * @param args the arguments to use when creating the new instance
 * @return a new instance of the implementation class mapped to <b>interfazz</b>
 */
public <T> T createInstance(Class<T> interfazz, Object... args) {
    Class<T> clazz = (Class<T>) mapping.get(interfazz);
    if (clazz == null) {
        throw new NoFactoryDefinitionException(
                "No factory is defined for class " + interfazz.getCanonicalName());
    }
    try {
        T instance = (T) ConstructorUtils.invokeConstructor(clazz, args);
        return interfazz.cast(instance);
    } catch (ClassCastException e) {
        throw new InvalidMappingValuesException(
                "invalid factory configuration, class " + clazz.getCanonicalName(), e);
    } catch (Exception e) {
        throw new RuntimeException(e.getMessage(), e);
    }

}

From source file:de.dfki.kiara.jsonrpc.JsonRpcProtocol.java

@Override
public InterfaceCodeGen createInterfaceCodeGen(final ConnectionBase connection) {
    final JsonRpcProtocol thisProtocol = this;
    return new InterfaceCodeGen() {
        @Override// ww w. ja  v a 2  s  .  co  m
        public <T> T generateInterfaceImpl(Class<T> interfaceClass, InterfaceMapping<T> mapping) {
            Object impl = Proxy.newProxyInstance(interfaceClass.getClassLoader(),
                    new Class<?>[] { interfaceClass, RemoteInterface.class },
                    new DefaultInvocationHandler(connection, mapping, thisProtocol));
            return interfaceClass.cast(impl);
        }
    };
}

From source file:com.amazonaws.mturk.service.axis.AWSService.java

/**
 * //ww  w  .ja va 2 s.  co m
 * @param m - Message structure which contains the details for making wsdl operation call 
 * @return Reply structure containing results and errors from the wsdl operation call 
 * @throws ServiceException
 */
public Reply executeRequestMessage(Message m) throws ServiceException {
    String axisMethodName = m.getMethodName();
    Object requests = m.getRequests();
    String credential = m.getCredential();
    String resultAccessorName = m.getResultAccessorName();
    try {
        Class bodyClass;
        Class responseClass;
        Class requestClass;
        Object body;

        // Construct the request body
        bodyClass = Class.forName(getPackagePrefix() + axisMethodName);
        body = bodyClass.newInstance();

        responseClass = Class.forName(getPackagePrefix() + axisMethodName + RESPONSE_SUFFIX);
        requestClass = Class.forName(getPackagePrefix() + axisMethodName + REQUEST_SUFFIX);

        Class requestArrayClass = Array.newInstance(requestClass, 0).getClass();
        Object requestArray = requestArrayClass.cast(requests);

        Method setRequest = bodyClass.getMethod(SET_REQUEST_METHOD_NAME, new Class[] { requestArrayClass });
        setRequest.invoke(body, requestArray);

        Calendar now = null;
        String signature = null;

        synchronized (AWSService.class) {
            Method setAWSAccessKeyId = bodyClass.getMethod(SET_AWS_ACCESS_KEY_ID_METHOD_NAME,
                    STRING_CLASS_ARRAY);
            setAWSAccessKeyId.invoke(body, getAWSAccessKeyId());

            Method setValidate = bodyClass.getMethod(SET_VALIDATE_METHOD_NAME, STRING_CLASS_ARRAY);
            setValidate.invoke(body, (Object) null);

            if (credential != null && credential.length() > 0) {
                Method setCredential = bodyClass.getMethod(SET_CREDENTIAL_METHOD_NAME, STRING_CLASS_ARRAY);
                setCredential.invoke(body, credential);
            }

            Method setTimestamp = bodyClass.getMethod(SET_TIMESTAMP_METHOD_NAME, CALENDAR_CLASS_ARRAY);
            now = Calendar.getInstance();
            setTimestamp.invoke(body, now);

            // Create the signature
            Method setSignature = bodyClass.getMethod(SET_SIGNATURE_METHOD_NAME, STRING_CLASS_ARRAY);
            signature = getSigner().sign(getServiceName(), axisMethodName, now);

            setSignature.invoke(body, signature);
        }

        Object response = responseClass.newInstance();

        String axisClassMethodName = axisMethodName.substring(0, 1).toLowerCase() + axisMethodName.substring(1);
        Method axisMethod = getPort().getClass().getMethod(axisClassMethodName, new Class[] { bodyClass });

        try {
            // Execute the request and get a response
            response = axisMethod.invoke(getPort(), body);
        } catch (InvocationTargetException e) {
            if (e.getCause() instanceof AxisFault) {
                //errors due to throttling are inside AxisFault. Get those if present
                AxisFault fault = (AxisFault) e.getCause();

                String httpResponse = fault.getFaultCode().getLocalPart();
                List<String> errorCodes = new ArrayList<String>();
                errorCodes.add(httpResponse);

                // When Axis encounters networking errors, it sets the fault code to
                // {http://xml.apache.org/axis/}HTTP
                // In this case it sets the error code from the http response in
                // the "HttpErrorCode" element of the fault details
                // If this is the case, add it to the error codes so the SDK
                // can be configured to retry for specific response codes
                if (AXIS_HTTP_FAULT.equals(fault.getFaultCode())) {
                    Element faultElement = fault.lookupFaultDetail(AXIS_HTTP_ERROR_CODE);
                    if (faultElement != null && faultElement.getFirstChild() != null) {
                        errorCodes.add(faultElement.getFirstChild().getNodeValue());
                    }
                }

                throw new InternalServiceException(e.getCause(), errorCodes);
            }
            throw new ServiceException(e.getCause());
        }

        // Extract the Operation Request
        Method getOperationRequest = responseClass.getMethod(GET_OPERATION_REQUEST_METHOD_NAME);
        Object operationRequest = getOperationRequest.invoke(response);

        // Extract the Errors
        Method getErrors = operationRequest.getClass().getMethod(GET_ERRORS_METHOD_NAME);
        Object errors = getErrors.invoke(operationRequest);
        Object[] results = null;

        if (errors != null) {
            return new Reply(results, errors, getRequestId(operationRequest));
        }

        Method getResult = responseClass.getMethod(GET_PREFIX + resultAccessorName);
        results = (Object[]) getResult.invoke(response);

        if (results == null || results.length == 0) {
            throw new ServiceException("Empty result, unknown error.");
        }

        for (int i = 0; i < results.length; i++) {
            Object result = results[i];

            Method getRequest = result.getClass().getMethod(GET_REQUEST_METHOD_NAME);
            Object request = getRequest.invoke(result);

            getErrors = request.getClass().getMethod(GET_ERRORS_METHOD_NAME);
            errors = getErrors.invoke(request);

            if (errors != null) {
                break; //get only the first error
            }
        }
        return new Reply(results, errors, getRequestId(operationRequest));

    } catch (ClassNotFoundException e) {
        throw new ServiceException(e);
    } catch (IllegalAccessException e) {
        throw new ServiceException(e);
    } catch (InstantiationException e) {
        throw new ServiceException(e);
    } catch (NoSuchMethodException e) {
        throw new ServiceException(e);
    } catch (InvocationTargetException e) {
        throw new ServiceException(e.getCause());
    }
}

From source file:com.cuubez.visualizer.processor.ConfigurationProcessor.java

private <T> T unMarshal(String rootNode, String content, Class<T> targetClass) {
    XStream xStream = new XStream(new DomDriver());
    xStream.processAnnotations(Configuration.class);
    xStream.alias(rootNode, targetClass);
    xStream.alias("group", Group.class);
    xStream.alias("http-code", HttpCode.class);
    xStream.alias("resource", Resource.class);
    xStream.alias("variable", Variable.class);
    return targetClass.cast(xStream.fromXML(content));
}