List of usage examples for java.lang Class cast
@SuppressWarnings("unchecked") @HotSpotIntrinsicCandidate public T cast(Object obj)
From source file:org.pivotal.gemfire.pdx.GemFireJsonToPdxToObjectDataAccessIntegrationTest.java
protected <T> T fromPdx(Object pdxInstance, Class<T> toType) { try {// ww w .ja v a 2 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)", nullSafeClassName(pdxInstance))); } } catch (IOException e) { throw new RuntimeException(String.format("Failed to convert PDX to object of type (%1$s)", toType), e); } }
From source file:org.solmix.runtime.support.spring.SpringBeanProvider.java
/** * {@inheritDoc}/* w w w.j av a 2 s.c o m*/ * * @see org.solmix.api.bean.ConfiguredBeanProvider#getBeansOfType(java.lang.Class) */ @Override public <T> Collection<? extends T> getBeansOfType(Class<T> type) { Set<String> s = new LinkedHashSet<String>(Arrays.asList(context.getBeanNamesForType(type, false, false))); s.removeAll(passThroughs); List<T> lst = new LinkedList<T>(); for (String n : s) { lst.add(type.cast(context.getBean(n, type))); } if (context.getParent() != null) { lst.addAll(_doGetBeansOfType(context.getParent(), type)); } if (original != null) { Collection<? extends T> origs = original.getBeansOfType(type); if (origs != null) lst.addAll(origs); } return lst; }
From source file:com.sdl.odata.datasource.jpa.mapper.AnnotationJPAEntityMapper.java
private <T> T jpaEntityToOData(final Object jpaEntity, Class<T> odataEntityClass, final EntityDataModel entityDataModel, final Map<Object, Object> visitedEntities) throws ODataDataSourceException { // If we already have entity in map, then it is a cyclic link, just return stored entity if (visitedEntities.containsKey(jpaEntity)) { return odataEntityClass.cast(visitedEntities.get(jpaEntity)); }/*from w w w . j a va2s. co m*/ final Class<?> sourceClass = jpaEntity.getClass(); checkAnnotationPresent(odataEntityClass, ODataJPAEntity.class); final StructuredType structType = (StructuredType) entityDataModel.getType(odataEntityClass); LOG.debug("Mapping JPA entity to OData: {} => {}", sourceClass.getName(), odataEntityClass.getName()); // Create new instance of OData entity final T odataEntity = newInstance(odataEntityClass); //add visited entity to map visitedEntities.put(jpaEntity, odataEntity); // Copy field values from JPA entity to OData entity visitProperties(entityDataModel, structType, new JPAPropertyVisitor() { @Override public void visit(StructuralProperty property, String jpaFieldName) throws ODataDataSourceException { Object jpaValue = readField(getField(sourceClass, jpaFieldName), jpaEntity); Object odataValue = jpaValue; // If the value is not null and the property is of a structured type, then map value(s) recursively if (jpaValue != null && isStructuredType(getPropertyType(entityDataModel, property))) { Class<?> targetType = getPropertyType(entityDataModel, property).getJavaType(); if (property.isCollection()) { Collection<Object> result = createPropertyCollection(property); for (Object element : (Iterable<?>) jpaValue) { result.add(jpaEntityToOData(element, targetType, entityDataModel, visitedEntities)); } odataValue = result; } else { odataValue = jpaEntityToOData(jpaValue, targetType, entityDataModel, visitedEntities); } } setPropertyValue(property, odataEntity, odataValue); } }); return odataEntity; }
From source file:de.openknowledge.jaxrs.versioning.conversion.InterversionConverter.java
public <T> T convertToHigherVersion(Class<T> targetType, Object source, String sourceVersion) { SupportedVersion supportedVersion = targetType.getAnnotation(SupportedVersion.class); if (supportedVersion == null) { throw new IllegalVersionException(sourceVersion); }//from ww w . j a va2s . co m if (supportedVersion.version().equals(sourceVersion)) { mapper.map(source); return targetType.cast(source); } if (supportedVersion.previous() == Object.class) { throw new IllegalVersionException(sourceVersion); } Object previousVersion = convertToHigherVersion(supportedVersion.previous(), source, sourceVersion); return map(previousVersion, targetType, new DefaultVersionContext()); }
From source file:eu.squadd.reflections.mapper.ServiceModelTranslator.java
private static boolean assignPropertyValue(PropertyDescriptor sourceProp, Object sourceValue, PropertyDescriptor destProp, Object destInstance) { if (sourceValue == null) { System.out.println("Null value found, assignment skipped"); return true; }// w w w. j a v a 2 s . c om boolean result = false; Class<?> sourceType = sourceProp.getPropertyType(); Method getter = sourceProp.getReadMethod(); Class<?> destType = destProp.getPropertyType(); Method setter = destProp.getWriteMethod(); try { if (destType.isInterface() || destType.isArray() || destType.isEnum()) { if (Collection.class.isAssignableFrom(sourceType) && Collection.class.isAssignableFrom(destType)) assignCollectionValue(getter, sourceValue, destType, setter, destInstance); else if (Map.class.isAssignableFrom(sourceType) && Map.class.isAssignableFrom(destType)) assignMapValue(getter, sourceValue, setter, destInstance); else assignMixedTypesValue(sourceType, getter, sourceValue, destType, setter, destInstance); } else if (destType.isInstance(sourceValue) || destType.isPrimitive()) setter.invoke(destInstance, sourceValue); else if (destType.isMemberClass()) setter.invoke(destInstance, sourceValue); else if (destType.isAssignableFrom(sourceType)) setter.invoke(destInstance, destType.cast(sourceValue)); else { //if (ClassUtils.isInnerClass(destType)) { Object member = transposeModel(sourceType, destType, sourceValue); member = destType.cast(member); setter.invoke(destInstance, member); } result = true; } catch (IllegalArgumentException ex) { System.out.println("Looks like type mismatch, source type: " + sourceType + ", dest type: " + destType); Logger.getLogger(ServiceModelTranslator.class.getName()).log(Level.SEVERE, null, ex); } catch (InvocationTargetException | IllegalAccessException ex) { Logger.getLogger(ServiceModelTranslator.class.getName()).log(Level.SEVERE, null, ex); } return result; }
From source file:com.activecq.api.ActiveForm.java
/** * Get value from this.data//from www . java 2 s .co m * * @param <T> * @param key * @param type * @return */ public <T> T get(String key, Class<T> type) { if (this.has(key)) { if (type != null) { return type.cast(this.data.get(key)); } } return null; }
From source file:be.fedict.eid.dss.model.bean.ConfigurationBean.java
/** * {@inheritDoc}/* ww w. j a va2 s . c om*/ */ public void setValue(ConfigProperty configProperty, String index, Object value) { String propertyValue; if (null != value) { Class<?> expectedType = configProperty.getType(); Class<?> type = value.getClass(); if (!expectedType.isAssignableFrom(type)) { throw new IllegalArgumentException("value has incorrect type: " + type.getClass().getName()); } Object castedValue = expectedType.cast(value); if (expectedType.isEnum()) { Enum<?> enumValue = (Enum<?>) castedValue; propertyValue = enumValue.name(); } else { propertyValue = castedValue.toString(); if (propertyValue.trim().isEmpty()) { propertyValue = null; } } } else { propertyValue = null; } String propertyName = getPropertyName(configProperty, index); ConfigPropertyEntity configPropertyEntity = this.entityManager.find(ConfigPropertyEntity.class, propertyName); if (null == configPropertyEntity) { configPropertyEntity = new ConfigPropertyEntity(propertyName, propertyValue); this.entityManager.persist(configPropertyEntity); } else { configPropertyEntity.setValue(propertyValue); } }
From source file:com.github.adejanovski.cassandra.jdbc.CassandraStatement.java
public <T> T unwrap(Class<T> iface) throws SQLException { if (iface.isInstance(this)) return iface.cast(this); throw new SQLFeatureNotSupportedException(String.format(NO_INTERFACE, iface.getSimpleName())); }
From source file:com.lazyloading.tag.util.ProviderUtil.java
/** * Util function to get the object created in SpringBeanFactory * This can largely be used to obtain objects of DataAccess Layer * /*w w w . j av a 2 s.c o m*/ * * @param claz Singleton class whose object needs t0 be fetced from SpringBeanFactory * @return <T> Instance of the class * @throws UnsupportedOperationException * @throws BeansException */ public <T> T getBeanByType(final Class<T> claz) throws UnsupportedOperationException, BeansException { ctx = LazyApplicationContextAware.getApplicationContext(); Map beansOfType = ctx.getBeansOfType(claz); final int size = beansOfType.size(); switch (size) { case 0: throw new UnsupportedOperationException("No bean found of type" + claz); case 1: String name = (String) beansOfType.keySet().iterator().next(); return claz.cast(ctx.getBean(name, claz)); default: throw new UnsupportedOperationException("Ambigious beans found of type" + claz); } }
From source file:cc.creativecomputing.events.CCListenerManager.java
/** * Creates an EventListenerSupport object which supports the provided listener interface using the specified class * loader to create the JDK dynamic proxy. * //from www.j a v a 2 s. com * @param listenerInterface the listener interface. * @param classLoader the class loader. * * @throws NullPointerException if <code>listenerInterface</code> or <code>classLoader</code> is <code>null</code>. * @throws IllegalArgumentException if <code>listenerInterface</code> is not an interface. */ public CCListenerManager(Class<ListenerType> listenerInterface, ClassLoader classLoader) { Validate.notNull(listenerInterface, "Listener interface cannot be null."); Validate.notNull(classLoader, "ClassLoader cannot be null."); Validate.isTrue(listenerInterface.isInterface(), "Class {0} is not an interface", listenerInterface.getName()); _myProxy = listenerInterface.cast(Proxy.newProxyInstance(classLoader, new Class[] { listenerInterface }, new ProxyInvocationHandler())); }