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.codelanx.codelanxlib.util.Reflections.java

/**
 * Returns a "default value" of -1 or {@code false} for a default type's
 * class or autoboxing class. Will return {@code null} if not relevant to
 * primitives/*w  ww .j  a v a 2 s .c o  m*/
 *
 * @since 0.1.0
 * @version 0.1.0
 *
 * @param <T> The type of the primitive
 * @param c The primitive class
 * @return The default value, or {@code null} if not a primitive
 */
public static <T> T defaultPrimitiveValue(Class<T> c) {
    if (c.isPrimitive() || Primitives.isWrapperType(c)) {
        c = Primitives.unwrap(c);
        T back;
        if (c == boolean.class) {
            back = c.cast(false);
        } else if (c == char.class) { //god help me
            back = c.cast((char) -1);
        } else if (c == float.class) {
            back = c.cast(-1F);
        } else if (c == long.class) {
            back = c.cast(-1L);
        } else if (c == double.class) {
            back = c.cast(-1D);
        } else if (c == int.class) {
            back = c.cast(-1); //ha
        } else if (c == short.class) {
            back = c.cast((short) -1);
        } else if (c == byte.class) {
            back = c.cast((byte) -1);
        }
    }
    return null;
}

From source file:de.pribluda.android.jsonmarshaller.JSONUnmarshaller.java

/**
 * TODO: provide support for nested JSON objects
 * TODO: provide support for embedded JSON Arrays
 *
 * @param jsonObject//from w w w.  java2 s .  com
 * @param beanToBeCreatedClass
 * @param <T>
 * @return
 * @throws IllegalAccessException
 * @throws InstantiationException
 * @throws JSONException
 * @throws NoSuchMethodException
 * @throws java.lang.reflect.InvocationTargetException
 */
@SuppressWarnings({ "unchecked", "rawtypes" })
public static <T> T unmarshall(JSONObject jsonObject, Class<T> beanToBeCreatedClass)
        throws IllegalAccessException, InstantiationException, JSONException, NoSuchMethodException,
        InvocationTargetException {
    T value = beanToBeCreatedClass.getConstructor().newInstance();

    Iterator keys = jsonObject.keys();
    while (keys.hasNext()) {
        String key = (String) keys.next();
        Object field = jsonObject.get(key);

        //  capitalise to standard setter pattern
        String methodName = SETTER_PREFIX + key.substring(0, 1).toUpperCase() + key.substring(1);

        //System.err.println("method name:" + methodName);

        Method method = getCandidateMethod(beanToBeCreatedClass, methodName);

        if (method != null) {
            Class clazz = method.getParameterTypes()[0];

            // discriminate based on type
            if (field.equals(JSONObject.NULL)) {
                method.invoke(value, clazz.cast(null));
            } else if (field instanceof String) {
                // check if we're an enum
                if (clazz.isEnum()) {
                    Object enm = clazz.getMethod("valueOf", String.class).invoke(null, field);
                    try {
                        beanToBeCreatedClass.getMethod(methodName, clazz).invoke(value, enm);
                        continue;
                    } catch (NoSuchMethodException e) {
                        // that means there was no such method, proceed
                    }
                }

                // string shall be used directly, either to set or as constructor parameter (if suitable)
                try {
                    beanToBeCreatedClass.getMethod(methodName, String.class).invoke(value, field);
                    continue;
                } catch (NoSuchMethodException e) {
                    // that means there was no such method, proceed
                }
                // or maybe there is method with suitable parameter?
                if (clazz.isPrimitive() && primitves.get(clazz) != null) {
                    clazz = primitves.get(clazz);
                }
                try {
                    method.invoke(value, clazz.getConstructor(String.class).newInstance(field));
                } catch (NoSuchMethodException nsme) {
                    // we are failed here,  but so what? be lenient
                }

            }
            // we are done with string
            else if (clazz.isArray() || clazz.isAssignableFrom(List.class)) {
                // JSON array corresponds either to array type, or to some collection
                if (field instanceof JSONObject) {
                    JSONArray array = new JSONArray();
                    array.put(field);
                    field = array;
                }

                // we are interested in arrays for now
                if (clazz.isArray()) {
                    // populate field value from JSON Array
                    Object fieldValue = populateRecursive(clazz, field);
                    method.invoke(value, fieldValue);
                } else if (clazz.isAssignableFrom(List.class)) {
                    try {
                        Type type = method.getGenericParameterTypes()[0];
                        if (type instanceof ParameterizedType) {
                            Type param = ((ParameterizedType) type).getActualTypeArguments()[0];
                            if (param instanceof Class) {
                                Class c = (Class) param;

                                // populate field value from JSON Array
                                Object fieldValue = populateRecursiveList(clazz, c, field);
                                method.invoke(value, fieldValue);
                            }
                        }
                    } catch (Exception e) {
                        // failed
                    }
                }

            } else if (field instanceof JSONObject) {
                // JSON object means nested bean - process recursively
                method.invoke(value, unmarshall((JSONObject) field, clazz));
            } else if (clazz.equals(Date.class)) {
                method.invoke(value, new Date((Long) field));
            } else {

                // fallback here,  types not yet processed will be
                // set directly ( if possible )
                // TODO: guard this? for better leniency
                method.invoke(value, field);
            }

        }
    }
    return value;
}

From source file:edu.sdsc.scigraph.neo4j.GraphUtil.java

static <T> Set<T> getPropertiesAsSet(Object value, Class<T> type) {
    Set<T> set = new HashSet<>();
    if (value.getClass().isArray()) {
        List<Object> objects = new ArrayList<>();
        for (int i = 0; i < Array.getLength(value); i++) {
            objects.add(Array.get(value, i));
        }/*from www.  j a v  a  2  s .c  o  m*/
        for (Object o : objects) {
            set.add(type.cast(o));
        }
    } else {
        set.add(type.cast(value));
    }
    return set;
}

From source file:com.amazonaws.services.lambda.invoke.LambdaInvokerFactory.java

/**
 * Creates a new Lambda invoker implementing the given interface and wrapping the given
 * {@code AWSLambda} client./*from w  w  w .ja v a  2 s .  co m*/
 *
 * @param interfaceClass
 *            the interface to implement
 * @param awsLambda
 *            the lambda client to use for making remote calls
 */
public static <T> T build(Class<T> interfaceClass, AWSLambda awsLambda) {
    Object proxy = Proxy.newProxyInstance(interfaceClass.getClassLoader(), new Class<?>[] { interfaceClass },
            new LambdaInvocationHandler(interfaceClass, awsLambda));

    return interfaceClass.cast(proxy);
}

From source file:com.shenit.commons.utils.DataUtils.java

/**
 * Cast?/*w  w  w .  ja  va 2  s  .  c  om*/
 * @param o
 * @param clazz
 * @return
 */
public static <T> T cast(Object o, Class<? extends T> clazz) {
    if (o == null || clazz == null || !clazz.isAssignableFrom(o.getClass()))
        return null;
    return clazz.cast(o);
}

From source file:com.omertron.subbabaapi.tools.ApiBuilder.java

/**
 * Get the wrapper based on the function
 *
 * @param <T>/* w ww .  j av  a2  s  .  c om*/
 * @param clazz
 * @param function
 * @param query
 * @param searchType
 * @return
 */
private static <T> T getWrapper(Class<T> clazz, SearchFunction function, String query, SearchType searchType)
        throws SubBabaException {
    URL url = buildUrl(function, query, searchType);
    try {
        final DigestedResponse response = getResponse(url);
        Object wrapper = MAPPER.readValue(response.getContent(), clazz);
        return clazz.cast(wrapper);
    } catch (JsonParseException | JsonMappingException ex) {
        throw new SubBabaException(ApiExceptionType.MAPPING_FAILED, "Failed to parse object", url, ex);
    } catch (IOException ex) {
        throw new SubBabaException(ApiExceptionType.CONNECTION_ERROR, "Error retrieving URL", url, ex);
    }
}

From source file:com.lolay.citygrid.BaseInvoker.java

protected static <T> T parseResults(Class<T> type, Response response) throws InvokerException {
    if (Response.Status.OK.getStatusCode() != response.getStatus()
            && Response.Status.BAD_REQUEST.getStatusCode() != response.getStatus()) {
        throw new RuntimeException(String.format("Can only parse 200 and 400 responses, the reponse was %s",
                response.getStatus()));//ww w  .ja v  a 2 s  .c  om
    }

    if (response.getEntity() != null && response.getEntity().getClass().equals(type)) {
        return type.cast(response.getEntity());
    } else if (response.getEntity() instanceof ErrorResults) {
        throw new InvokerException(ErrorResults.class.cast(response.getEntity()));
    } else if (response.getEntity() instanceof InputStream) {
        InputStream stream = InputStream.class.cast(response.getEntity());
        Object results = null;
        try {
            JAXBContext context = JAXBContext.newInstance(type, ErrorResults.class);
            results = context.createUnmarshaller().unmarshal(stream);
        } catch (JAXBException e) {
            throw new RuntimeException("Problem unmarshalling the entity", e);
        }
        if (results != null && results.getClass().equals(type)) {
            return type.cast(results);
        } else {
            throw new InvokerException(ErrorResults.class.cast(results));
        }
    } else {
        throw new RuntimeException(
                String.format("Do not know how to parse %s", response.getEntity().getClass()));
    }
}

From source file:com.moviejukebox.tools.StringTools.java

/**
 * Cast a generic list to a specific class
 *
 * See:/*from   w w w . j  a v  a  2  s . co m*/
 * http://stackoverflow.com/questions/367626/how-do-i-fix-the-expression-of-type-list-needs-unchecked-conversion
 *
 * @param <T>
 * @param objClass
 * @param c
 * @return
 */
public static <T> List<T> castList(Class<? extends T> objClass, Collection<?> c) {
    List<T> r = new ArrayList<>(c.size());
    for (Object o : c) {
        r.add(objClass.cast(o));
    }
    return r;
}

From source file:Utils.java

/**
 * Create a typesafe filter of an unchecked enumeration.
 * @param rawEnum an unchecked enumeration
 * @param type the desired enumeration type
 * @param strict if false, elements which are not null but not assignable to the requested type are omitted;
 *               if true, {@link ClassCastException} may be thrown from an enumeration operation
 * @return an enumeration guaranteed to contain only objects of the requested type (or null)
 *//* w  w  w .j av  a  2 s.  c o m*/
public static <E> Enumeration<E> checkedEnumerationByFilter(Enumeration rawEnum, final Class<E> type,
        final boolean strict) {
    @SuppressWarnings("unchecked")
    Enumeration<Object> _rawEnum = rawEnum;
    return Enumerations.<Object, E>filter(_rawEnum, new Enumerations.Processor<Object, E>() {
        public E process(Object o, Collection<Object> ignore) {
            if (o == null) {
                return null;
            } else {
                try {
                    return type.cast(o);
                } catch (ClassCastException x) {
                    if (strict) {
                        throw x;
                    } else {
                        return null;
                    }
                }
            }
        }
    });
}

From source file:org.apache.vxquery.app.util.RestUtils.java

/**
 * Maps the object in the string representation to a java object. To map json
 * entities, this method use {@link ObjectMapper}. For XML this method use
 * {@link Unmarshaller}.//from  w w w.jav a2  s.  c o m
 * 
 * @param entity
 *            string representation of the object
 * @param type
 *            the class to which the string needs to be mapped to
 * @param contentType
 *            json or XML
 * @param <T>
 *            content's class type
 * @return mapped object
 * @throws IOException
 * @throws JAXBException
 */
public static <T> T mapEntity(String entity, Class<T> type, String contentType)
        throws IOException, JAXBException {
    if (contentType == null) {
        contentType = CONTENT_TYPE_JSON;
    }

    switch (contentType) {
    case CONTENT_TYPE_XML:
        JAXBContext jaxbContext = JAXBContext.newInstance(type);
        Unmarshaller unmarshaller = jaxbContext.createUnmarshaller();
        return type.cast(unmarshaller.unmarshal(new StringReader(entity)));
    case CONTENT_TYPE_JSON:
    default:
        ObjectMapper jsonMapper = new ObjectMapper();
        return jsonMapper.readValue(entity, type);
    }
}