List of usage examples for java.beans PropertyDescriptor getWriteMethod
public synchronized Method getWriteMethod()
From source file:com.heren.turtle.server.utils.TransUtils.java
public Object U2IObject(Object obj) { Object newObj = new Object(); if (obj == null) { return null; }//from w w w. j av a 2s . c o m try { BeanInfo beanInfo = Introspector.getBeanInfo(obj.getClass()); PropertyDescriptor[] propertyDescriptors = beanInfo.getPropertyDescriptors(); for (PropertyDescriptor property : propertyDescriptors) { String key = property.getName(); if (!key.equals("class")) { Method getter = property.getReadMethod(); Object value = getter.invoke(obj); if (value instanceof String) { Method setter = property.getWriteMethod(); Object newValue = U2I((String) value); setter.invoke(obj, newValue); } } } newObj = obj; } catch (Exception e) { e.printStackTrace(); } return newObj; }
From source file:org.openengsb.core.ekb.common.EDBConverter.java
/** * Converts an EDBObject to a model by analyzing the object and trying to call the corresponding setters of the * model./*from www . j a v a2 s. c o m*/ */ private Object convertEDBObjectToUncheckedModel(Class<?> model, EDBObject object) { if (!checkEDBObjectModelType(object, model)) { return null; } EDBConverterUtils.filterEngineeringObjectInformation(object, model); List<OpenEngSBModelEntry> entries = new ArrayList<OpenEngSBModelEntry>(); for (PropertyDescriptor propertyDescriptor : ModelUtils.getPropertyDescriptorsForClass(model)) { if (propertyDescriptor.getWriteMethod() == null || propertyDescriptor.getName().equals(ModelUtils.MODEL_TAIL_FIELD_NAME)) { continue; } Object value = getValueForProperty(propertyDescriptor, object); Class<?> propertyClass = propertyDescriptor.getPropertyType(); if (propertyClass.isPrimitive()) { entries.add(new OpenEngSBModelEntry(propertyDescriptor.getName(), value, ClassUtils.primitiveToWrapper(propertyClass))); } else { entries.add(new OpenEngSBModelEntry(propertyDescriptor.getName(), value, propertyClass)); } } for (Map.Entry<String, EDBObjectEntry> objectEntry : object.entrySet()) { EDBObjectEntry entry = objectEntry.getValue(); Class<?> entryType; try { entryType = model.getClassLoader().loadClass(entry.getType()); entries.add(new OpenEngSBModelEntry(entry.getKey(), entry.getValue(), entryType)); } catch (ClassNotFoundException e) { LOGGER.error("Unable to load class {} of the model tail", entry.getType()); } } return ModelUtils.createModel(model, entries); }
From source file:org.tros.utils.PropertiesInitializer.java
/** * Initialize from JSON if possible./*w ww . j a v a 2 s .c o m*/ */ private void initializeFromJson() { try { java.util.Enumeration<URL> resources = ClassLoader.getSystemClassLoader() .getResources(this.getClass().getCanonicalName().replace('.', '/') + ".json"); ArrayList<URL> urls = new ArrayList<>(); //HACK: semi sort classpath to put "files" first and "jars" second. //this has an impact once we are workin in tomcat where //the classes in tomcat are not stored in a jar. while (resources.hasMoreElements()) { URL url = resources.nextElement(); if (url.toString().startsWith("file:")) { urls.add(0, url); } else { boolean added = false; for (int ii = 0; !added && ii < urls.size(); ii++) { if (!urls.get(ii).toString().startsWith("file:")) { urls.add(ii, url); added = true; } } if (!added) { urls.add(url); } } } //reverse the list, so that the item found first in the //classpath will be the last one run though and thus //be the one to set the final value Collections.reverse(urls); PropertyDescriptor[] props = Introspector.getBeanInfo(this.getClass()).getPropertyDescriptors(); for (URL url : urls) { try { PropertiesInitializer obj = (PropertiesInitializer) readValue(url.openStream(), this.getClass()); for (PropertyDescriptor p : props) { if (p.getWriteMethod() != null && p.getReadMethod() != null && p.getReadMethod().getDeclaringClass() != Object.class) { Object val = p.getReadMethod().invoke(obj); if (val != null) { p.getWriteMethod().invoke(this, val); } } } } catch (NullPointerException | IOException | IllegalArgumentException | InvocationTargetException | IllegalAccessException ex) { LOGGER.debug(null, ex); } } } catch (IOException ex) { } catch (IntrospectionException ex) { LOGGER.warn(null, ex); } }
From source file:org.mypsycho.beans.DefaultInvoker.java
/** * <p>//from w w w .java 2 s . c o m * Return an accessible property setter method for this property, if there * is one; otherwise return <code>null</code>. * </p> * <p> * <strong>FIXME</strong> - Does not work with DynaBeans. * </p> * * @param clazz The class of the read method will be invoked on * @param descriptor Property descriptor to return a setter for * @return The write method */ Method getWriteMethod(Class<?> clazz, PropertyDescriptor descriptor) { return (MethodUtils.getAccessibleMethod(clazz, descriptor.getWriteMethod())); }
From source file:org.onebusaway.nyc.presentation.impl.NycConfigurationServiceImpl.java
private ConfigurationBean loadSettings() { if (_path == null || !_path.exists()) return new ConfigurationBean(); try {/*from www .j a va 2s. c o m*/ Properties properties = new Properties(); properties.load(new FileReader(_path)); ConfigurationBean bean = new ConfigurationBean(); BeanInfo beanInfo = Introspector.getBeanInfo(ConfigurationBean.class); for (PropertyDescriptor desc : beanInfo.getPropertyDescriptors()) { String name = desc.getName(); Object value = properties.getProperty(name); if (value != null) { Converter converter = ConvertUtils.lookup(desc.getPropertyType()); value = converter.convert(desc.getPropertyType(), value); Method m = desc.getWriteMethod(); m.invoke(bean, value); } } return bean; } catch (Exception ex) { throw new IllegalStateException("error loading configuration from properties file " + _path, ex); } }
From source file:net.zcarioca.zcommons.config.data.BeanPropertySetterFactory.java
/** * Gets a collection of {@link BeanPropertySetter} to configure the bean. * * @param bean The bean to configure./*from w w w . jav a 2 s . c o m*/ * @return Returns a collection of {@link BeanPropertySetter}. * @throws ConfigurationException */ public Collection<BeanPropertySetter> getPropertySettersForBean(Object bean) throws ConfigurationException { List<BeanPropertySetter> setters = new ArrayList<BeanPropertySetter>(); Map<String, PropertyDescriptor> descriptors = new HashMap<String, PropertyDescriptor>(); Class<?> beanClass = bean.getClass(); try { BeanInfo beanInfo = Introspector.getBeanInfo(beanClass); for (PropertyDescriptor desc : beanInfo.getPropertyDescriptors()) { Method reader = desc.getReadMethod(); Method writer = desc.getWriteMethod(); Field field = getField(beanClass, desc); if (reader != null) { descriptors.put(desc.getDisplayName(), desc); } if (writer != null) { if (writer.isAnnotationPresent(ConfigurableAttribute.class)) { setters.add(new WriterBeanPropertySetter(bean, desc, field, writer.getAnnotation(ConfigurableAttribute.class))); descriptors.remove(desc.getDisplayName()); } if (reader != null && reader.isAnnotationPresent(ConfigurableAttribute.class)) { setters.add(new WriterBeanPropertySetter(bean, desc, field, reader.getAnnotation(ConfigurableAttribute.class))); descriptors.remove(desc.getDisplayName()); } } } } catch (Throwable t) { throw new ConfigurationException("Could not introspect bean class", t); } do { Field[] fields = beanClass.getDeclaredFields(); for (Field field : fields) { if (field.isAnnotationPresent(ConfigurableAttribute.class)) { if (descriptors.containsKey(field.getName()) && descriptors.get(field.getName()).getWriteMethod() != null) { PropertyDescriptor desc = descriptors.get(field.getName()); setters.add(new WriterBeanPropertySetter(bean, desc, field, field.getAnnotation(ConfigurableAttribute.class))); } else { setters.add(new FieldBeanPropertySetter(bean, null, field, field.getAnnotation(ConfigurableAttribute.class))); } } else if (descriptors.containsKey(field.getName())) { // the annotation may have been set on the getter, not the field PropertyDescriptor desc = descriptors.get(field.getName()); if (desc.getReadMethod().isAnnotationPresent(ConfigurableAttribute.class)) { setters.add(new FieldBeanPropertySetter(bean, desc, field, desc.getReadMethod().getAnnotation(ConfigurableAttribute.class))); } } } } while ((beanClass = beanClass.getSuperclass()) != null); return setters; }
From source file:com.icsshs.datatransfer.database.impl.QueryBeanProcessor.java
/** * Calls the setter method on the target object for the given property. * If no setter method exists for the property, this method does nothing. * @param target The object to set the property on. * @param prop The property to set.//from w w w.j a v a 2 s . co m * @param value The value to pass into the setter. * @throws SQLException if an error occurs setting the property. */ private void callSetter(Object target, PropertyDescriptor prop, Object value) throws SQLException { Method setter = prop.getWriteMethod(); if (setter == null) { return; } Class<?>[] params = setter.getParameterTypes(); try { // convert types for some popular ones if (value != null) { if (value instanceof java.util.Date) { if (params[0].getName().equals("java.sql.Date")) { value = new java.sql.Date(((java.util.Date) value).getTime()); } else if (params[0].getName().equals("java.sql.Time")) { value = new java.sql.Time(((java.util.Date) value).getTime()); } else if (params[0].getName().equals("java.sql.Timestamp")) { value = new java.sql.Timestamp(((java.util.Date) value).getTime()); } } } // Don't call setter if the value object isn't the right type if (this.isCompatibleType(value, params[0])) { setter.invoke(target, new Object[] { value }); } else { throw new SQLException("Cannot set " + prop.getName() + ": incompatible types."); } } catch (IllegalArgumentException e) { throw new SQLException("Cannot set " + prop.getName() + ": " + e.getMessage()); } catch (IllegalAccessException e) { throw new SQLException("Cannot set " + prop.getName() + ": " + e.getMessage()); } catch (InvocationTargetException e) { throw new SQLException("Cannot set " + prop.getName() + ": " + e.getMessage()); } }
From source file:com.khubla.cbean.CBeanType.java
/** * build the map of getters and setters to properties *///from w w w . j ava 2 s . co m private void buildGetterSetterMap() { final PropertyUtilsBean propertyUtilsBean = new PropertyUtilsBean(); final PropertyDescriptor[] propertyDescriptors = propertyUtilsBean.getPropertyDescriptors(clazz); if (null != propertyDescriptors) { for (int i = 0; i < propertyDescriptors.length; i++) { final PropertyDescriptor propertyDescriptor = propertyDescriptors[i]; if (null != propertyDescriptor.getReadMethod()) { getterMap.put(propertyDescriptor.getReadMethod().getName(), propertyDescriptor.getName()); } if (null != propertyDescriptor.getWriteMethod()) { setterMap.put(propertyDescriptor.getWriteMethod().getName(), propertyDescriptor.getName()); } } } }
From source file:info.magnolia.jcr.node2bean.impl.TypeMappingImpl.java
@Override public PropertyTypeDescriptor getPropertyTypeDescriptor(Class<?> beanClass, String propName) { PropertyTypeDescriptor dscr = null;/* w w w . j a v a 2 s . c o m*/ String key = beanClass.getName() + "." + propName; dscr = propertyTypes.get(key); if (dscr != null) { return dscr; } dscr = new PropertyTypeDescriptor(); dscr.setName(propName); PropertyDescriptor[] descriptors = PropertyUtils.getPropertyDescriptors(beanClass); Method writeMethod = null; for (PropertyDescriptor descriptor : descriptors) { if (descriptor.getName().equals(propName)) { // may be null for indexed properties Class<?> propertyType = descriptor.getPropertyType(); writeMethod = descriptor.getWriteMethod(); if (propertyType != null) { dscr.setType(getTypeDescriptor(propertyType, writeMethod)); } // set write method dscr.setWriteMethod(writeMethod); // set add method int numberOfParameters = dscr.isMap() ? 2 : 1; dscr.setAddMethod(getAddMethod(beanClass, propName, numberOfParameters)); break; } } if (dscr.getType() != null) { // we have discovered type for property if (dscr.isMap() || dscr.isCollection()) { List<Class<?>> parameterTypes = new ArrayList<Class<?>>(); // this will contain collection types (for map key/value type, for collection value type) if (dscr.getWriteMethod() != null) { parameterTypes = inferGenericTypes(dscr.getWriteMethod()); } if (dscr.getAddMethod() != null && parameterTypes.size() == 0) { // here we know we don't have setter or setter doesn't have parameterized type // but we have add method so we take parameters from it parameterTypes = Arrays.asList(dscr.getAddMethod().getParameterTypes()); // rather set it to null because when we are here we will use add method dscr.setWriteMethod(null); } if (parameterTypes.size() > 0) { // we resolved types if (dscr.isMap()) { dscr.setCollectionKeyType(getTypeDescriptor(parameterTypes.get(0))); dscr.setCollectionEntryType(getTypeDescriptor(parameterTypes.get(1))); } else { // collection dscr.setCollectionEntryType(getTypeDescriptor(parameterTypes.get(0))); } } } else if (dscr.isArray()) { // for arrays we don't need to discover its parameter from set/add method // we just take it via Class#getComponentType() method dscr.setCollectionEntryType(getTypeDescriptor(dscr.getType().getType().getComponentType())); } } propertyTypes.put(key, dscr); return dscr; }
From source file:com.qcadoo.model.internal.classconverter.ModelXmlToClassConverterTest.java
private void verifyField(final PropertyDescriptor propertyDescriptor, final Class<?> type, final boolean readable, final boolean writable) { assertEquals(type, propertyDescriptor.getPropertyType()); if (writable) { assertNotNull(propertyDescriptor.getWriteMethod()); } else {// w w w . j av a 2 s. c o m assertNull(propertyDescriptor.getWriteMethod()); } if (readable) { assertNotNull(propertyDescriptor.getReadMethod()); } else { assertNull(propertyDescriptor.getReadMethod()); } }