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.avanza.ymer.TestSpaceObjectFakeConverter.java

static DocumentConverter create() {
    return DocumentConverter.create(new DocumentConverter.Provider() {
        @Override/*from w ww  .  j a v a 2 s.c o  m*/
        public BasicDBObject convertToDBObject(Object type) {
            if (type instanceof TestSpaceObject) {
                TestSpaceObject testSpaceObject = (TestSpaceObject) type;
                BasicDBObject dbObject = new BasicDBObject();
                dbObject.put("_id", testSpaceObject.getId());
                if (testSpaceObject.getMessage() != null) {
                    dbObject.put("message", testSpaceObject.getMessage());
                }
                return dbObject;
            } else if (type instanceof TestSpaceOtherObject) {
                TestSpaceOtherObject testSpaceOtherObject = (TestSpaceOtherObject) type;
                BasicDBObject dbObject = new BasicDBObject();
                dbObject.put("_id", testSpaceOtherObject.getId());
                if (testSpaceOtherObject.getMessage() != null) {
                    dbObject.put("message", testSpaceOtherObject.getMessage());
                }
                return dbObject;
            } else if (type instanceof TestReloadableSpaceObject) {
                TestReloadableSpaceObject testSpaceObject = (TestReloadableSpaceObject) type;
                BasicDBObject dbObject = new BasicDBObject();
                dbObject.put("_id", testSpaceObject.getId());
                dbObject.put("patched", testSpaceObject.isPatched());
                dbObject.put("versionID", testSpaceObject.getVersionID());
                if (testSpaceObject.getLatestRestoreVersion() != null) {
                    dbObject.put("latestRestoreVersion", testSpaceObject.getLatestRestoreVersion());
                }
                return dbObject;
            } else {
                throw new RuntimeException("Unknown object type: " + type.getClass());
            }
        }

        @Override
        public <T> T convert(Class<T> toType, BasicDBObject document) {
            if (toType.equals(TestSpaceObject.class)) {
                TestSpaceObject testSpaceObject = new TestSpaceObject();
                testSpaceObject.setId(document.getString("_id"));
                testSpaceObject.setMessage(document.getString("message"));
                return toType.cast(testSpaceObject);
            } else if (toType.equals(TestReloadableSpaceObject.class)) {
                TestReloadableSpaceObject testSpaceObject = new TestReloadableSpaceObject();
                testSpaceObject.setId(document.getInt("_id"));
                if (document.containsField("patched")) {
                    testSpaceObject.setPatched(document.getBoolean("patched"));
                }
                testSpaceObject.setVersionID(document.getInt("versionID"));
                if (document.containsField("latestRestoreVersion")) {
                    testSpaceObject.setLatestRestoreVersion(document.getInt("latestRestoreVersion"));
                }
                return toType.cast(testSpaceObject);
            } else {
                throw new RuntimeException("Unknown object type: " + toType);
            }
        }

        @Override
        public Object convert(Object type) {
            if (type instanceof Number) {
                return type;
            }
            return type.toString();
        }

        @Override
        public Query toQuery(Object template) {
            throw new UnsupportedOperationException();
        }
    });

}

From source file:org.bremersee.sms.ExtensionUtils.java

/**
 * Transforms a XML node into an object.
 * //from  www .j  a va 2  s. c  o m
 * @param node
 *            the XML node
 * @param valueType
 *            the class of the target object
 * @param jaxbContext
 *            the {@link JAXBContext} (can be null)
 * @return the target object
 * @throws JAXBException
 *             if transformation fails
 */
public static <T> T xmlNodeToObject(Node node, Class<T> valueType, JAXBContext jaxbContext)
        throws JAXBException {
    if (node == null) {
        return null;
    }
    Validate.notNull(valueType, "valueType must not be null");
    if (jaxbContext == null) {
        jaxbContext = getJaxbContext(valueType);
    }
    return valueType.cast(jaxbContext.createUnmarshaller().unmarshal(node));
}

From source file:Main.java

public static <T> List<T> readList(String root, String filename, Class<T> type) {
    List<T> objects = new ArrayList<>();
    File file = new File(root, filename);
    try {/*  w  w w  . java  2  s  .  c o  m*/
        if (file.exists()) {
            FileInputStream fis = new FileInputStream(file);
            ObjectInputStream ois = new ObjectInputStream(fis);
            Object object = ois.readObject();
            if (object instanceof List) {
                for (Object it : (List) object) {
                    objects.add(type.cast(it));
                }
            }
            ois.close();
            return Collections.unmodifiableList(objects);
        }
    } catch (Exception e) {
        Log.e(TAG, String.format("Failed to read [%s]", file), e);
    }
    return Collections.emptyList();
}

From source file:grails.util.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  . ja va2 s .c  o m
 * @param type the required type
 * @param <T> the type parameter
 * @return the value retrieved by ConfigurationHolder.flatConfig
 */
public static <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:org.bremersee.sms.ExtensionUtils.java

/**
 * Transforms a XML node or a JSON map into an object.
 * //  w w  w  .ja  v  a 2  s  . c om
 * @param xmlNodeOrJsonMap
 *            the XML node or JSON map
 * @param valueType
 *            the class of the target object
 * @param jaxbContextOrObjectMapper
 *            a {@link JAXBContext} or a {@link ObjectMapper} (can be null)
 * @return the target object
 * @throws Exception
 *             if transformation fails
 * @deprecated Use
 *             {@link ExtensionUtils#transform(Object, Class, JAXBContext, ObjectMapper)}
 *             instead.
 */
@Deprecated
@SuppressWarnings("unchecked")
public static <T> T transform(Object xmlNodeOrJsonMap, Class<T> valueType, Object jaxbContextOrObjectMapper)
        throws Exception {
    if (xmlNodeOrJsonMap == null) {
        return null;
    }
    Validate.notNull(valueType, "valueType must not be null");
    if (valueType.isAssignableFrom(xmlNodeOrJsonMap.getClass())) {
        return valueType.cast(xmlNodeOrJsonMap);
    }
    if (xmlNodeOrJsonMap instanceof Node) {
        JAXBContext jaxbContext;
        if (jaxbContextOrObjectMapper != null && jaxbContextOrObjectMapper instanceof JAXBContext) {
            jaxbContext = (JAXBContext) jaxbContextOrObjectMapper;
        } else {
            jaxbContext = null;
        }
        return xmlNodeToObject((Node) xmlNodeOrJsonMap, valueType, jaxbContext);
    }
    if (xmlNodeOrJsonMap instanceof Map) {
        ObjectMapper objectMapper;
        if (jaxbContextOrObjectMapper != null && jaxbContextOrObjectMapper instanceof ObjectMapper) {
            objectMapper = (ObjectMapper) jaxbContextOrObjectMapper;
        } else {
            objectMapper = null;
        }
        return jsonMapToObject((Map<String, Object>) xmlNodeOrJsonMap, valueType, objectMapper);
    }
    throw new IllegalArgumentException(
            "xmlNodeOrJsonMap must be of type " + Node.class.getName() + " or of type " + Map.class.getName());
}

From source file:org.anon.smart.d2cache.store.repository.hbase.SilentObjectCreator.java

public static <T> T create(Class<T> clazz, Class<? super T> parent) {
    try {/*  w  w w.j a v a 2 s  . c  om*/
        if (Collection.class.isAssignableFrom(clazz)) {
            return (T) CollectionFactory.createCollection(clazz, 10);

        }
        ReflectionFactory rf = ReflectionFactory.getReflectionFactory();
        Constructor objDef = parent.getDeclaredConstructor();
        Constructor intConstr = rf.newConstructorForSerialization(clazz, objDef);
        return clazz.cast(intConstr.newInstance());
    } catch (RuntimeException e) {
        throw e;
    } catch (Exception e) {
        throw new IllegalStateException("Cannot create object", e);
    }
}

From source file:org.bremersee.sms.ExtensionUtils.java

/**
 * Transforms a XML node or a JSON map into an object.
 * /*w  w  w  .  j a  va2  s .  c o  m*/
 * @param xmlNodeOrJsonMap
 *            the XML node or JSON map
 * @param valueType
 *            the class of the target object
 * @param jaxbContext
 *            the {@link JAXBContext} (can be null)
 * @param objectMapper
 *            the JSON object mapper (optional)
 * @return the target object
 * @throws Exception
 *             if transformation fails
 */
@SuppressWarnings("unchecked")
public static <T> T transform(Object xmlNodeOrJsonMap, Class<T> valueType, JAXBContext jaxbContext,
        ObjectMapper objectMapper) throws Exception {
    if (xmlNodeOrJsonMap == null) {
        return null;
    }
    Validate.notNull(valueType, "valueType must not be null");
    if (valueType.isAssignableFrom(xmlNodeOrJsonMap.getClass())) {
        return valueType.cast(xmlNodeOrJsonMap);
    }
    if (xmlNodeOrJsonMap instanceof Node) {
        return xmlNodeToObject((Node) xmlNodeOrJsonMap, valueType, jaxbContext);
    }
    if (xmlNodeOrJsonMap instanceof Map) {
        return jsonMapToObject((Map<String, Object>) xmlNodeOrJsonMap, valueType, objectMapper);
    }
    throw new IllegalArgumentException("xmlNodeOrJsonMap must be of type " + valueType + ", "
            + Node.class.getName() + " or of type " + Map.class.getName());
}

From source file:com.healthmarketscience.rmiio.RemoteRetry.java

/**
 * Checks the given exception against the given Exception type, throwing if
 * the given exception is an instanceof the given type. Otherwise, returns.
 *//*from  w  w  w .ja va  2s  .c om*/
private static <ExType extends Throwable> void throwIfMatchesType(Throwable throwable, Class<ExType> throwType)
        throws ExType {
    if (throwType.isInstance(throwable)) {
        throw throwType.cast(throwable);
    }
}

From source file:edu.vt.middleware.gator.log4j.Log4jConfigUtils.java

/**
 * Instantiate a new instance of the given class name.
 *
 * @param  <T>  Type of class to instantiate.
 * @param  clazz  Class of type to instantiate.
 * @param  name  Fully-qualified class name.
 *
 * @return  New instance of specified class.
 *
 * @throws  ConfigurationException  On configuration errors.
 *//*  www  .j a va 2s  .  c o  m*/
public static <T> T instantiate(final Class<T> clazz, final String name) throws ConfigurationException {
    Class<?> c;
    try {
        LOGGER.trace("Instantiating new instance of " + name);
        c = Class.forName(name);
    } catch (ClassNotFoundException e) {
        throw new ConfigurationException(String.format("Class %s not found.", name));
    }
    try {
        return clazz.cast(c.newInstance());
    } catch (InstantiationException e) {
        throw new ConfigurationException(String.format("Cannot instantiate %s.", name), e);
    } catch (IllegalAccessException e) {
        throw new ConfigurationException(
                String.format("Cannot instantiate %s -- constructor not accessible.", name), e);
    } catch (ClassCastException e) {
        throw new ConfigurationException(String.format("%s is not an instance of %s", name, clazz), e);
    }
}

From source file:com.snapdeal.archive.util.ArchivalUtil.java

/**
 * Returns a map where key is string and value is object. Caution should be made to use this method iff the property is String 
 * @param objects/* w  ww. j  a  v  a  2  s  .  c o m*/
 * @param propertyName
 * @return
 */
public static <K, T> Map<K, T> getPropertyObjectMap(List<T> objects, String propertyName,
        Class<K> propertyClass) {
    Map<K, T> propertyObjectMap = new HashMap<>();
    for (T t : objects) {
        Object value = null;
        try {
            Field field = t.getClass().getDeclaredField(propertyName);
            field.setAccessible(true);
            value = field.get(t);
            // value = PropertyUtils.getProperty(t, propertyName);
            K k = (K) propertyClass.cast(value);
            propertyObjectMap.put(k, t);
        } catch (IllegalAccessException | NoSuchFieldException | SecurityException e) {
            e.printStackTrace();
        }
    }
    return propertyObjectMap;
}