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.adobe.phonegap.contentsync.Sync.java

private String getCookies(final String target) {
    boolean gotCookie = false;
    String cookie = null;/*from  w  w w  .j a  v a 2s. c  o  m*/
    Class webViewClass = webView.getClass();
    try {
        Method gcmMethod = webViewClass.getMethod("getCookieManager");
        Class iccmClass = gcmMethod.getReturnType();
        Method gcMethod = iccmClass.getMethod("getCookie");

        cookie = (String) gcMethod.invoke(iccmClass.cast(gcmMethod.invoke(webView)), target);

        gotCookie = true;
    } catch (NoSuchMethodException e) {
    } catch (IllegalAccessException e) {
    } catch (InvocationTargetException e) {
    } catch (ClassCastException e) {
    }

    if (!gotCookie) {
        cookie = CookieManager.getInstance().getCookie(target);
    }

    return cookie;
}

From source file:be.fgov.kszbcss.rhq.websphere.mbean.MBeanClient.java

public <T> T getProxy(Class<T> iface) {
    synchronized (proxies) {
        Object proxy = proxies.get(iface);
        if (proxy == null) {
            if (log.isDebugEnabled()) {
                log.debug("Creating dynamic proxy for MBean " + locator);
            }/*from  w ww .j  a  va 2 s.  c om*/
            for (Method method : iface.getMethods()) {
                if (!throwsException(method, JMException.class)
                        || !throwsException(method, ConnectorException.class)) {
                    throw new IllegalArgumentException(iface.getName() + " is not a valid proxy class: method "
                            + method.getName() + " must declare JMException and ConnectorException");
                }
            }
            proxy = Proxy.newProxyInstance(MBeanClient.class.getClassLoader(),
                    new Class<?>[] { iface, MBeanClientProxy.class }, new MBeanClientInvocationHandler(this));
            proxies.put(iface, proxy);
        }
        return iface.cast(proxy);
    }
}

From source file:org.kohsuke.github.Requester.java

private <T> T parse(Class<T> type, T instance) throws IOException {
    InputStreamReader r = null;//from w  w w . j ava  2s  . c om
    int responseCode = -1;
    String responseMessage = null;
    try {
        responseCode = uc.getResponseCode();
        responseMessage = uc.getResponseMessage();
        if (responseCode == 304) {
            return null; // special case handling for 304 unmodified, as the content will be ""
        }
        if (responseCode == 204 && type != null && type.isArray()) {
            // no content
            return type.cast(Array.newInstance(type.getComponentType(), 0));
        }

        r = new InputStreamReader(wrapStream(uc.getInputStream()), "UTF-8");
        String data = IOUtils.toString(r);
        if (type != null)
            try {
                return MAPPER.readValue(data, type);
            } catch (JsonMappingException e) {
                throw (IOException) new IOException("Failed to deserialize " + data).initCause(e);
            }
        if (instance != null)
            return MAPPER.readerForUpdating(instance).<T>readValue(data);
        return null;
    } catch (FileNotFoundException e) {
        // java.net.URLConnection handles 404 exception has FileNotFoundException, don't wrap exception in HttpException
        // to preserve backward compatibility
        throw e;
    } catch (IOException e) {
        throw new HttpException(responseCode, responseMessage, uc.getURL(), e);
    } finally {
        IOUtils.closeQuietly(r);
    }
}

From source file:name.wramner.jmstools.analyzer.DataProvider.java

private <T> T findWithCachedScalarResult(String sql, Class<T> cls) {
    Object cachedValue = _cache.get(sql);
    if (cachedValue == null) {
        try (Statement stat = _conn.createStatement(); ResultSet rs = stat.executeQuery(sql)) {
            if (rs.next()) {
                cachedValue = rs.getObject(1);
            }//from w ww.j  a va 2  s .  c o  m
            _cache.put(sql, cachedValue);
        } catch (SQLException e) {
            throw new UncheckedSqlException(e);
        }
    }
    return cachedValue != null ? cls.cast(cachedValue) : null;
}

From source file:org.apache.servicemix.camel.nmr.AttachmentTest.java

private <T> T createPort(QName serviceName, QName portName, Class<T> serviceEndpointInterface,
        boolean enableMTOM) throws Exception {
    Bus bus = BusFactory.getDefaultBus();
    ReflectionServiceFactoryBean serviceFactory = new JaxWsServiceFactoryBean();
    serviceFactory.setBus(bus);//from   w  ww.j a v a  2  s  .c  o m
    serviceFactory.setServiceName(serviceName);
    serviceFactory.setServiceClass(serviceEndpointInterface);
    serviceFactory.setWsdlURL(getClass().getResource("/wsdl/mtom_xop.wsdl"));
    Service service = serviceFactory.create();
    EndpointInfo ei = service.getEndpointInfo(portName);
    JaxWsEndpointImpl jaxwsEndpoint = new JaxWsEndpointImpl(bus, service, ei);
    SOAPBinding jaxWsSoapBinding = new SOAPBindingImpl(ei.getBinding());
    jaxWsSoapBinding.setMTOMEnabled(enableMTOM);

    Client client = new ClientImpl(bus, jaxwsEndpoint);
    InvocationHandler ih = new JaxWsClientProxy(client, jaxwsEndpoint.getJaxwsBinding());
    Object obj = Proxy.newProxyInstance(serviceEndpointInterface.getClassLoader(),
            new Class[] { serviceEndpointInterface, BindingProvider.class }, ih);
    return serviceEndpointInterface.cast(obj);
}

From source file:ddf.catalog.data.impl.MetacardImpl.java

/**
 * The brains of the operation -- does the interaction with the map or the wrapped metacard.
 *
 * @param <T>           the type of the Attribute value expected
 * @param attributeName the name of the {@link Attribute} to retrieve
 * @param returnType    the class that the value of the {@link ddf.catalog.data.AttributeType} is expected to be bound to
 * @return the value of the requested {@link Attribute} name
 */// ww  w .j ava  2  s  . co  m
protected <T> T requestData(String attributeName, Class<T> returnType) {

    Attribute attribute = getAttribute(attributeName);

    if (attribute == null) {
        if (LOGGER.isDebugEnabled()) {
            LOGGER.debug("Attribute " + attributeName + " was not found, returning null");
        }
        return null;
    }

    Serializable data = attribute.getValue();

    if (returnType.isAssignableFrom(data.getClass())) {
        return returnType.cast(data);
    } else {
        if (LOGGER.isDebugEnabled()) {
            LOGGER.debug(data.getClass().toString() + " can not be assigned to " + returnType.toString());
        }
    }

    return null;
}

From source file:com.twitter.elephantbird.pig.piggybank.Invoker.java

private static <T> T convertToExpectedArg(Class<T> klass, Object obj) throws ExecException {
    if (ARRAY_CLASSES.contains(klass)) {
        DataBag dbag = (DataBag) obj;/*from   w  w  w  .j a v  a  2s.  c o m*/
        if (STRING_ARRAY_CLASS.equals(klass)) {
            List<String> dataList = Lists.newArrayList();
            for (Tuple t : dbag) {
                dataList.add((String) t.get(0));
            }
            String[] dataArray = new String[dataList.size()];
            for (int i = 0; i < dataList.size(); i++) {
                dataArray[i] = dataList.get(i);
            }
            obj = dataArray;
        } else {
            List<Number> dataList = bagToNumberList(dbag);
            if (DOUBLE_ARRAY_CLASS.equals(klass)) {
                double[] dataArray = new double[dataList.size()];
                for (int i = 0; i < dataList.size(); i++) {
                    dataArray[i] = dataList.get(i).doubleValue();
                }
                obj = dataArray;
            } else if (INT_ARRAY_CLASS.equals(klass)) {
                int[] dataArray = new int[dataList.size()];
                for (int i = 0; i < dataList.size(); i++) {
                    dataArray[i] = dataList.get(i).intValue();
                }
                obj = dataArray;
            } else if (FLOAT_ARRAY_CLASS.equals(klass)) {
                float[] dataArray = new float[dataList.size()];
                for (int i = 0; i < dataList.size(); i++) {
                    dataArray[i] = dataList.get(i).floatValue();
                }
                obj = dataArray;
            } else if (LONG_ARRAY_CLASS.equals(klass)) {
                long[] dataArray = new long[dataList.size()];
                for (int i = 0; i < dataList.size(); i++) {
                    dataArray[i] = dataList.get(i).longValue();
                }
                obj = dataArray;
            }
        }
    }
    try {
        return klass.cast(obj);
    } catch (ClassCastException e) {
        LOG.error("Error in dynamic argument processing. Casting to: " + klass + " from: " + obj.getClass(), e);
        throw new ExecException(e);
    }
}

From source file:com.github.jakubkolar.autobuilder.impl.NamedResolver.java

@Nullable
@Override//from w w w  .  j  av a2 s.com
public <T> T resolve(Class<T> type, Optional<Type> typeInfo, String name, Collection<Annotation> annotations) {
    // If type is primitive like int.class, we must use its wrapper type
    // because the wrapper type is used as a part of the key in the namedValues
    // and also because int.class cannot be used in the end to 'unbox' the result
    // (same in BuiltInResolvers.primitiveTypeResolver, you would get ClassCastException)
    Class<T> wrappedType = Primitives.wrap(type);

    @SuppressWarnings("rawtypes")
    RegisteredValue rv = namedValues.get(ImmutablePair.of(name, (Class) wrappedType));

    if (rv == null) {
        // TODO: try to lookup null, which this way applies to _any_ type
        rv = namedValues.get(ImmutablePair.of(name, (Class) null));
        if (rv == null) {
            throw new UnsupportedOperationException(String.format(
                    "There is no registered named value with name %s and type %s", name, type.getSimpleName()));
        }
    }

    for (Annotation requiredAnnotation : rv.getAnnotations()) {
        if (!annotations.contains(requiredAnnotation)) {
            throw new UnsupportedOperationException(String.format(
                    "The named value with name %s and type %s requires annotations %s, "
                            + "but only these annotations were present: %s",
                    name, type.getSimpleName(), requiredAnnotation, annotations));
        }
    }

    try {
        return wrappedType.cast(rv.getValue());
    } catch (ClassCastException e) {
        throw new UnsupportedOperationException(
                String.format("Named value %s cannot be converted to the required type %s because of: %s", name,
                        type.getSimpleName(), e.getMessage()),
                e);
    }
}

From source file:com.adeptj.modules.data.jpa.core.AbstractJpaRepository.java

/**
 * {@inheritDoc}//  w w  w.  ja  v  a2s.  c om
 */
@Override
public <T> T getScalarResultOfType(Class<T> resultClass, QueryType type, String query, List<Object> posParams) {
    EntityManager em = JpaUtil.createEntityManager(this.getEntityManagerFactory());
    try {
        switch (type) {
        case JPA:
            TypedQuery<T> typedQuery = em.createQuery(query, resultClass);
            JpaUtil.bindQueryParams(typedQuery, posParams);
            return typedQuery.getSingleResult();
        case NATIVE:
            Query nativeQuery = em.createNativeQuery(query, resultClass);
            JpaUtil.bindQueryParams(nativeQuery, posParams);
            return resultClass.cast(nativeQuery.getSingleResult());
        default:
            throw new IllegalStateException("Invalid QueryType!!");
        }
    } catch (Exception ex) { // NOSONAR
        throw new JpaException(ex);
    } finally {
        JpaUtil.closeEntityManager(em);
    }
}