Example usage for java.beans PropertyDescriptor getWriteMethod

List of usage examples for java.beans PropertyDescriptor getWriteMethod

Introduction

In this page you can find the example usage for java.beans PropertyDescriptor getWriteMethod.

Prototype

public synchronized Method getWriteMethod() 

Source Link

Document

Gets the method that should be used to write the property value.

Usage

From source file:org.fudgemsg.mapping.JavaBeanBuilder.java

/**
 * Creates a new {@link JavaBeanBuilder} for a class.
 * //from   ww  w.  j a v  a 2  s.c o  m
 * @param <T> class the builder should process
 * @param clazz class the builder should process
 * @return the {@code JavaBeanBuilder}
 */
/* package */ static <T> JavaBeanBuilder<T> create(final Class<T> clazz) {
    // customise the properties
    final ArrayList<JBProperty> propList = new ArrayList<JBProperty>();
    for (PropertyDescriptor prop : PropertyUtils.getPropertyDescriptors(clazz)) {
        // ignore the class
        if (prop.getName().equals("class"))
            continue;
        // check for FudgeFieldName annotations on either accessor or mutator
        FudgeFieldName annoName;
        FudgeFieldOrdinal annoOrdinal;
        String name = prop.getName();
        Integer ordinal = null;
        if (prop.getWriteMethod() != null) {
            // give up if it's a transient property
            if (TransientUtil.hasTransientAnnotation(prop.getWriteMethod()))
                continue;
            if ((annoName = prop.getWriteMethod().getAnnotation(FudgeFieldName.class)) != null)
                name = annoName.value();
            if ((annoOrdinal = prop.getWriteMethod().getAnnotation(FudgeFieldOrdinal.class)) != null) {
                ordinal = (int) annoOrdinal.value();
                if (annoOrdinal.noFieldName())
                    name = null;
            }
        }
        if (prop.getReadMethod() != null) {
            // give up if it's a transient property
            if (TransientUtil.hasTransientAnnotation(prop.getReadMethod()))
                continue;
            if ((annoName = prop.getReadMethod().getAnnotation(FudgeFieldName.class)) != null)
                name = annoName.value();
            if ((annoOrdinal = prop.getReadMethod().getAnnotation(FudgeFieldOrdinal.class)) != null) {
                ordinal = (int) annoOrdinal.value();
                if (annoOrdinal.noFieldName())
                    name = null;
            }
        }
        propList.add(new JBProperty(name, ordinal, prop.getReadMethod(), prop.getWriteMethod(),
                prop.getPropertyType()));
    }
    // try and find a constructor
    try {
        return new JavaBeanBuilder<T>(propList.toArray(new JBProperty[propList.size()]),
                clazz.getConstructor());
    } catch (SecurityException e) {
        // ignore
    } catch (NoSuchMethodException e) {
        // ignore
    }
    // otherwise bean behaviour (about 5 times slower!)
    return new JavaBeanBuilder<T>(propList.toArray(new JBProperty[propList.size()]), clazz.getName());
}

From source file:org.agnitas.service.csv.Toolkit.java

public static void setValueFromBean(Object bean, String fieldName, String value) {
    try {//  w ww.  j a  v a  2 s .c om
        PropertyDescriptor propertyDescriptor = getPropertyDescriptor(bean, fieldName);
        // This should never be null as it would be caused by a node representing an unknown property being popped whereas it
        // should never have been pushed in the first place!
        if (propertyDescriptor.getName().equals("customFields")) {
            final Map<String, String> customCollumnMappig = (Map<String, String>) propertyDescriptor
                    .getReadMethod().invoke(bean);
            customCollumnMappig.put(fieldName, value);
        } else {
            propertyDescriptor.getWriteMethod().invoke(bean, value);
        }
    } catch (Exception e) {
        AgnUtils.logger().warn(MessageFormat.format("Failed to set bean ({0}) property {1} with value {2}",
                bean, fieldName, value), e);
    }
}

From source file:es.logongas.ix3.util.ReflectionUtil.java

/**
 * Establecer el valor en un bena/* ww  w.j av a  2s . c  o m*/
 *
 * @param obj El objeto al que se establece el valor
 * @param propertyName El nombre de la propieda a establecer el valor. Se
 * permiten "subpropiedades" separadas por "."
 * @param value El valor a establecer.
 */
static public void setValueToBean(Object obj, String propertyName, Object value) {
    try {
        if ((propertyName == null) || (propertyName.trim().isEmpty())) {
            throw new RuntimeException("El parametro propertyName no puede ser null o estar vacio");
        }
        if (obj == null) {
            throw new RuntimeException("El parametro obj no puede ser null");
        }

        BeanInfo beanInfo = Introspector.getBeanInfo(obj.getClass());
        PropertyDescriptor[] propertyDescriptors = beanInfo.getPropertyDescriptors();

        String leftPropertyName; //El nombre de la propiedad antes del primer punto
        String rigthPropertyName; //El nombre de la propiedad antes del primer punto

        int indexPoint = propertyName.indexOf(".");
        if (indexPoint < 0) {
            leftPropertyName = propertyName;
            rigthPropertyName = null;
        } else if ((indexPoint > 0) && (indexPoint < (propertyName.length() - 1))) {
            leftPropertyName = propertyName.substring(0, indexPoint);
            rigthPropertyName = propertyName.substring(indexPoint + 1);
        } else {
            throw new RuntimeException("El punto no puede estar ni al principio ni al final");
        }

        Method readMethod = null;
        Method writeMethod = null;
        for (PropertyDescriptor propertyDescriptor : propertyDescriptors) {
            if (propertyDescriptor.getName().equals(leftPropertyName)) {
                readMethod = propertyDescriptor.getReadMethod();
                writeMethod = propertyDescriptor.getWriteMethod();
            }
        }

        if (rigthPropertyName != null) {
            if (readMethod == null) {
                throw new RuntimeException("No existe la propiedad de lectura:" + leftPropertyName);
            }
            Object valueProperty = readMethod.invoke(obj);
            setValueToBean(valueProperty, rigthPropertyName, value);
        } else {
            if (writeMethod == null) {
                throw new RuntimeException("No existe la propiedad de escritura:" + leftPropertyName);
            }
            writeMethod.invoke(obj, new Object[] { value });
        }

    } catch (Exception ex) {
        throw new RuntimeException("obj:" + obj + " propertyName=" + propertyName + " value=" + value, ex);
    }
}

From source file:org.paxml.util.ReflectUtils.java

/**
 * Set a property for a bean.// w  w w  .j a va  2s.  c  om
 * 
 * @param bean
 *            the bean
 * @param pd
 *            the property descriptor
 * @param value
 *            the property value
 */
public static void callSetter(Object bean, PropertyDescriptor pd, Object value) {

    Method setter = pd.getWriteMethod();
    if (setter == null) {
        throw new PaxmlRuntimeException(
                "Property '" + pd.getName() + "' is not settable on class: " + bean.getClass().getName());
    }

    value = coerceType(value, setter.getParameterTypes()[0]);
    try {
        setter.invoke(bean, value);
    } catch (Exception e) {
        throw new PaxmlRuntimeException("Cannot call setter on property: " + pd.getName(), e);
    }
}

From source file:it.geosolutions.geoserver.jms.impl.utils.BeanUtils.java

/**
 * This is a 'smart' (perform checks for some special cases) update function which should be used to copy of the properties for objects
 * of the catalog and configuration./*from   w  ww. j  a  v  a2s .  c  o m*/
 * 
 * @param <T> the type of the bean to update
 * @param info the bean instance to update
 * @param properties the list of string of properties to update
 * @param values the list of new values to update
 * 
 * @throws IllegalAccessException
 * @throws InvocationTargetException
 * @throws NoSuchMethodException
 */
public static <T> void smartUpdate(final T info, final List<String> properties, final List<Object> values)
        throws IllegalAccessException, InvocationTargetException, NoSuchMethodException {
    final Iterator<String> itPropertyName = properties.iterator();
    final Iterator<Object> itValue = values.iterator();
    while (itPropertyName.hasNext() && itValue.hasNext()) {
        String propertyName = itPropertyName.next();
        final Object value = itValue.next();

        PropertyDescriptor pd = PropertyUtils.getPropertyDescriptor(info, propertyName);
        // return null if there is no such descriptor
        if (pd == null) {
            // this is a special case used by the NamespaceInfoImpl setURI
            // the propertyName coming from the ModificationProxy is set to 'uRI'
            // lets set it to uri
            propertyName = propertyName.toUpperCase();
            pd = PropertyUtils.getPropertyDescriptor(info, propertyName);
            if (pd == null) {
                return;
            }
        }
        if (pd.getWriteMethod() != null) {
            PropertyUtils.setProperty(info, propertyName, value);
        } else {
            // T interface do not declare setter method for this property
            // lets use getter methods to get the property reference
            final Object property = PropertyUtils.getProperty(info, propertyName);

            // check type of property to apply new value
            if (Collection.class.isAssignableFrom(pd.getPropertyType())) {
                final Collection<?> liveCollection = (Collection<?>) property;
                liveCollection.clear();
                liveCollection.addAll((Collection) value);
            } else if (Map.class.isAssignableFrom(pd.getPropertyType())) {
                final Map<?, ?> liveMap = (Map<?, ?>) property;
                liveMap.clear();
                liveMap.putAll((Map) value);
            } else {
                if (CatalogUtils.LOGGER.isLoggable(java.util.logging.Level.SEVERE))
                    CatalogUtils.LOGGER.severe("Skipping unwritable property " + propertyName
                            + " with property type " + pd.getPropertyType());
            }
        }
    }
}

From source file:com.industrieit.ohr.OHRJavassister.java

private static boolean isInlineString(PropertyDescriptor pd) {
    return pd.getWriteMethod().isAnnotationPresent(InlineStringReify.class);
}

From source file:org.apache.cocoon.transformation.TagTransformer.java

private static Map getWriteMethodMap(Class beanClass) throws IntrospectionException {
    Map map = (Map) TAG_PROPERTIES_MAP.get(beanClass);
    if (map != null) {
        return map;
    }//from  w w  w .  j ava  2 s.c o m

    BeanInfo info = Introspector.getBeanInfo(beanClass);
    if (info != null) {
        PropertyDescriptor pds[] = info.getPropertyDescriptors();
        map = new HashMap(pds.length * 4 / 3, 1);
        for (int i = 0; i < pds.length; i++) {
            PropertyDescriptor pd = pds[i];
            String name = pd.getName();
            Method method = pd.getWriteMethod();
            Class type = pd.getPropertyType();
            if (type != String.class) // only String properties
                continue;
            map.put(name, method);
        }
    }
    TAG_PROPERTIES_MAP.put(beanClass, map);
    return map;
}

From source file:com.nortal.petit.beanmapper.BeanMappingUtils.java

/**
 * Adds an extended property to the BeanMapping. 
 * /* ww w  .  j  a va 2s .com*/
 * @param props
 * @param name
 * @param type
 * @param columnMapping
 * @return
 */
public static <B> Property<B, Object> initExtendedProperty(Map<String, Property<B, Object>> props, String name,
        Class<B> type, String columnMapping) {
    PropertyDescriptor pd = BeanUtils.getPropertyDescriptor(type, name);

    if (!isPropertyReadableAndWritable(pd)) {
        return null;
    }

    List<Annotation> ans = BeanMappingReflectionUtils.readAnnotations(type, pd.getName());

    Column column = BeanMappingReflectionUtils.getAnnotation(ans, Column.class);

    ReflectionProperty<B, Object> prop = new ReflectionProperty<B, Object>(name,
            (Class<Object>) pd.getPropertyType(),
            inferColumn(columnMapping != null ? columnMapping : name, column), pd.getWriteMethod(),
            pd.getReadMethod());

    if (column != null) {
        prop.readOnly(true);
    }

    if (BeanMappingReflectionUtils.getAnnotation(ans, Id.class) != null) {
        prop.setIdProperty(true);
    }

    if (useAdditionalConfiguration()) {
        prop.getConfiguration().setAnnotations(ans);
        if (Collection.class.isAssignableFrom(pd.getPropertyType())) {
            prop.getConfiguration().setCollectionTypeArguments(
                    ((ParameterizedType) pd.getReadMethod().getGenericReturnType()).getActualTypeArguments());
        }
    }

    if (BeanMappingReflectionUtils.getAnnotation(ans, Embedded.class) != null) {
        props.putAll(getCompositeProperties(prop, ans));
    } else {
        props.put(prop.name(), prop);
    }

    return prop;
}

From source file:io.uengine.util.ReflectionUtils.java

/**
 *  ?? ?  Setter ./* www  . j av a  2 s  .  c  o  m*/
 *
 * @param instance  ?
 * @param fieldName ? 
 * @return Setter
 * @throws io.uengine.common.exception.ServiceException Setter    
 */
public static Method getSetterMethod(Object instance, String fieldName) throws ServiceException {
    try {
        PropertyDescriptor propertyDescriptor = PropertyUtils.getPropertyDescriptor(instance, fieldName);
        return propertyDescriptor.getWriteMethod();
    } catch (Exception e) {
        String message = MessageFormatter
                .format("Cannot find setter method of '{}' in '{}'.", fieldName, instance.getClass().getName())
                .getMessage();
        throw new ServiceException(message, e);
    }
}

From source file:org.openflamingo.util.ReflectionUtils.java

/**
 *  ?? ?  Setter .//  w  w  w  .  j  ava2s. c o m
 *
 * @param instance  ?
 * @param fieldName ? 
 * @return Setter
 * @throws org.openflamingo.core.exception.WorkflowException Setter    
 */
public static Method getSetterMethod(Object instance, String fieldName) throws WorkflowException {
    try {
        PropertyDescriptor propertyDescriptor = PropertyUtils.getPropertyDescriptor(instance, fieldName);
        return propertyDescriptor.getWriteMethod();
    } catch (Exception e) {
        String message = MessageFormatter
                .format("Cannot find setter method of '{}' in '{}'.", fieldName, instance.getClass().getName())
                .getMessage();
        throw new WorkflowException(message, e);
    }
}