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.openflamingo.uploader.util.ReflectionUtils.java

/**
 *  ?? ?  Setter .//from  w w  w  . j a va 2 s .c o m
 *
 * @param instance  ?
 * @param fieldName ? 
 * @return Setter
 * @throws SystemException Setter    
 */
public static Method getSetterMethod(Object instance, String fieldName) throws SystemException {
    try {
        PropertyDescriptor propertyDescriptor = PropertyUtils.getPropertyDescriptor(instance, fieldName);
        return propertyDescriptor.getWriteMethod();
    } catch (Exception e) {
        throw new SystemException("[" + instance.getClass().getName() + "] ??  [" + fieldName
                + "] ? Setter ?  .", e);
    }
}

From source file:gr.interamerican.bo2.utils.JavaBeanUtils.java

/**
 * Sets the value of a property on an object.
 * /*  w  w w.j  a  va 2 s .c om*/
 * If the property has a setter method, then it will be called.
 * If the property does not have a setter method, the field
 * will be set. If there is no such field, then the method will
 * ignore it. <br/>
 * The method will box any {@link Exception} thrown during java reflection
 * calls inside a {@link RuntimeException}.
 * 
 * @param pd
 *            Descriptor of the property.
 * @param val
 *            New value for the field.
 * @param obj
 *            Object on which the field value is changed.
 */
static void setPropertyTyped(PropertyDescriptor pd, Object val, Object obj) {
    Method setter = pd.getWriteMethod();
    if (setter != null) {
        Object[] args = { val };
        ReflectionUtils.invoke(setter, obj, args);
    } else {
        String fieldName = pd.getName();
        try {
            Field field = obj.getClass().getDeclaredField(fieldName);
            field.setAccessible(true);
            ReflectionUtils.set(field, val, obj);
        } catch (NoSuchFieldException nse) {
            throw new RuntimeException(nse);
        }
    }
}

From source file:org.vulpe.view.tags.Functions.java

/**
 *
 * @param bean//from  w ww.jav  a 2 s .  c  o  m
 * @return
 */

public static List fieldsInBean(final Object bean) {
    final PropertyDescriptor pDescriptor[] = PropertyUtils.getPropertyDescriptors(bean);
    final List list = new ArrayList();
    for (PropertyDescriptor propertyDescriptor : pDescriptor) {
        if (propertyDescriptor.getReadMethod() == null || propertyDescriptor.getWriteMethod() == null) {
            continue;
        }

        list.add(propertyDescriptor.getName());
    }
    return list;
}

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

/**
 * Returns the initialized property./*from   w  ww .jav  a 2  s .com*/
 * In case of Embedded property the root property is returned for reference. Embedde properties themselves are expanded
 * in the props variable.
 * 
 * Null is returned if the property is not valid (either not readable/writable or Transient)
 * 
 * @param props
 * @param name
 * @param type
 */
public static <B> Property<B, Object> initProperty(Map<String, Property<B, Object>> props, String name,
        Class<B> type) {
    PropertyDescriptor pd = BeanUtils.getPropertyDescriptor(type, name);

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

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

    if (BeanMappingReflectionUtils.getAnnotation(ans, Transient.class) != null) {
        return null;
    }

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

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

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

    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:org.springframework.beans.BeanUtils.java

/**
 * Find a JavaBeans {@code PropertyDescriptor} for the given method,
 * with the method either being the read method or the write method for
 * that bean property.//from  w  w w. j  ava 2s  . c  om
 * @param method the method to find a corresponding PropertyDescriptor for
 * @param clazz the (most specific) class to introspect for descriptors
 * @return the corresponding PropertyDescriptor, or {@code null} if none
 * @throws BeansException if PropertyDescriptor lookup fails
 * @since 3.2.13
 */
@Nullable
public static PropertyDescriptor findPropertyForMethod(Method method, Class<?> clazz) throws BeansException {
    Assert.notNull(method, "Method must not be null");
    PropertyDescriptor[] pds = getPropertyDescriptors(clazz);
    for (PropertyDescriptor pd : pds) {
        if (method.equals(pd.getReadMethod()) || method.equals(pd.getWriteMethod())) {
            return pd;
        }
    }
    return null;
}

From source file:org.talend.dataprep.conversions.BeanConversionService.java

/**
 * The {@link BeanUtils#copyProperties(java.lang.Object, java.lang.Object)} method does <b>NOT</b> check if parametrized type
 * are compatible when copying values, this helper method performs this additional check and ignore copy of those values.
 *
 * @param source The source bean (from which values are read).
 * @param converted The target bean (to which values are written).
 *//*from  w  w  w .  j a  va 2  s . c o m*/
private static void copyBean(Object source, Object converted) {
    // Find property(ies) to ignore during copy.
    List<String> discardedProperties = new LinkedList<>();
    final BeanWrapper sourceBean = new BeanWrapperImpl(source);
    final BeanWrapper targetBean = new BeanWrapperImpl(converted);
    final PropertyDescriptor[] sourceProperties = sourceBean.getPropertyDescriptors();
    for (PropertyDescriptor sourceProperty : sourceProperties) {
        if (targetBean.isWritableProperty(sourceProperty.getName())) {
            final PropertyDescriptor targetProperty = targetBean
                    .getPropertyDescriptor(sourceProperty.getName());
            final Class<?> sourcePropertyType = sourceProperty.getPropertyType();
            final Class<?> targetPropertyType = targetProperty.getPropertyType();
            final Method readMethod = sourceProperty.getReadMethod();
            if (readMethod != null) {
                final Type sourceReturnType = readMethod.getGenericReturnType();
                final Method targetPropertyWriteMethod = targetProperty.getWriteMethod();
                if (targetPropertyWriteMethod != null) {
                    final Type targetReturnType = targetPropertyWriteMethod.getParameters()[0]
                            .getParameterizedType();
                    boolean valid = Object.class.equals(targetPropertyType)
                            || sourcePropertyType.equals(targetPropertyType)
                                    && sourceReturnType.equals(targetReturnType);
                    if (!valid) {
                        discardedProperties.add(sourceProperty.getName());
                    }
                }
            } else {
                discardedProperties.add(sourceProperty.getName());
            }
        }
    }

    // Perform copy
    BeanUtils.copyProperties(source, converted,
            discardedProperties.toArray(new String[discardedProperties.size()]));
}

From source file:org.springframework.beans.BeanUtils.java

/**
 * Copy the property values of the given source bean into the given target bean.
 * <p>Note: The source and target classes do not have to match or even be derived
 * from each other, as long as the properties match. Any bean properties that the
 * source bean exposes but the target bean does not will silently be ignored.
 * @param source the source bean//from w  w  w  .  j  ava 2 s .  c om
 * @param target the target bean
 * @param editable the class (or interface) to restrict property setting to
 * @param ignoreProperties array of property names to ignore
 * @throws BeansException if the copying failed
 * @see BeanWrapper
 */
private static void copyProperties(Object source, Object target, @Nullable Class<?> editable,
        @Nullable String... ignoreProperties) throws BeansException {

    Assert.notNull(source, "Source must not be null");
    Assert.notNull(target, "Target must not be null");

    Class<?> actualEditable = target.getClass();
    if (editable != null) {
        if (!editable.isInstance(target)) {
            throw new IllegalArgumentException("Target class [" + target.getClass().getName()
                    + "] not assignable to Editable class [" + editable.getName() + "]");
        }
        actualEditable = editable;
    }
    PropertyDescriptor[] targetPds = getPropertyDescriptors(actualEditable);
    List<String> ignoreList = (ignoreProperties != null ? Arrays.asList(ignoreProperties) : null);

    for (PropertyDescriptor targetPd : targetPds) {
        Method writeMethod = targetPd.getWriteMethod();
        if (writeMethod != null && (ignoreList == null || !ignoreList.contains(targetPd.getName()))) {
            PropertyDescriptor sourcePd = getPropertyDescriptor(source.getClass(), targetPd.getName());
            if (sourcePd != null) {
                Method readMethod = sourcePd.getReadMethod();
                if (readMethod != null && ClassUtils.isAssignable(writeMethod.getParameterTypes()[0],
                        readMethod.getReturnType())) {
                    try {
                        if (!Modifier.isPublic(readMethod.getDeclaringClass().getModifiers())) {
                            readMethod.setAccessible(true);
                        }
                        Object value = readMethod.invoke(source);
                        if (!Modifier.isPublic(writeMethod.getDeclaringClass().getModifiers())) {
                            writeMethod.setAccessible(true);
                        }
                        writeMethod.invoke(target, value);
                    } catch (Throwable ex) {
                        throw new FatalBeanException(
                                "Could not copy property '" + targetPd.getName() + "' from source to target",
                                ex);
                    }
                }
            }
        }
    }
}

From source file:org.sharegov.cirm.utils.GenUtils.java

@SuppressWarnings("unchecked")
public static <T> T cloneBean(T bean) {
    try {// www. j ava 2 s  .c  om
        T clone = (T) bean.getClass().newInstance();
        for (PropertyDescriptor desc : BonesOfBeans.getAllPropertyDescriptors(bean).values()) {
            if (desc.getReadMethod() == null || desc.getWriteMethod() == null)
                continue;
            BonesOfBeans.setProperty(clone, desc, BonesOfBeans.getProperty(bean, desc));
        }
        return clone;
    } catch (Exception ex) {
        throw new RuntimeException(ex);
    }
}

From source file:com.ms.commons.summer.web.util.json.JsonBeanUtils.java

/**
 * Creates a bean from a JSONObject, with the specific configuration.
 *//*from   w w  w .j a v a  2s .co  m*/
public static Object toBean(JSONObject jsonObject, Object root, JsonConfig jsonConfig) {
    if (jsonObject == null || jsonObject.isNullObject() || root == null) {
        return root;
    }

    Class rootClass = root.getClass();
    if (rootClass.isInterface()) {
        throw new JSONException("Root bean is an interface. " + rootClass);
    }

    Map classMap = jsonConfig.getClassMap();
    if (classMap == null) {
        classMap = Collections.EMPTY_MAP;
    }

    Map props = JSONUtils.getProperties(jsonObject);
    PropertyFilter javaPropertyFilter = jsonConfig.getJavaPropertyFilter();
    for (Iterator entries = jsonObject.names().iterator(); entries.hasNext();) {
        String name = (String) entries.next();
        Class type = (Class) props.get(name);
        Object value = jsonObject.get(name);
        if (javaPropertyFilter != null && javaPropertyFilter.apply(root, name, value)) {
            continue;
        }
        String key = JSONUtils.convertToJavaIdentifier(name, jsonConfig);
        try {
            PropertyDescriptor pd = PropertyUtils.getPropertyDescriptor(root, key);
            if (pd != null && pd.getWriteMethod() == null) {
                log.warn("Property '" + key + "' has no write method. SKIPPED.");
                continue;
            }

            if (!JSONUtils.isNull(value)) {
                if (value instanceof JSONArray) {
                    if (pd == null || List.class.isAssignableFrom(pd.getPropertyType())) {
                        Class targetClass = findTargetClass(key, classMap);
                        targetClass = targetClass == null ? findTargetClass(name, classMap) : targetClass;
                        Object newRoot = jsonConfig.getNewBeanInstanceStrategy().newInstance(targetClass, null);
                        List list = JSONArray.toList((JSONArray) value, newRoot, jsonConfig);
                        setProperty(root, key, list, jsonConfig);
                    } else {
                        Class innerType = JSONUtils.getInnerComponentType(pd.getPropertyType());
                        Class targetInnerType = findTargetClass(key, classMap);
                        if (innerType.equals(Object.class) && targetInnerType != null
                                && !targetInnerType.equals(Object.class)) {
                            innerType = targetInnerType;
                        }
                        Object newRoot = jsonConfig.getNewBeanInstanceStrategy().newInstance(innerType, null);
                        Object array = JSONArray.toArray((JSONArray) value, newRoot, jsonConfig);
                        if (innerType.isPrimitive() || JSONUtils.isNumber(innerType)
                                || Boolean.class.isAssignableFrom(innerType) || JSONUtils.isString(innerType)) {
                            array = JSONUtils.getMorpherRegistry()
                                    .morph(Array.newInstance(innerType, 0).getClass(), array);
                        } else if (!array.getClass().equals(pd.getPropertyType())) {
                            if (!pd.getPropertyType().equals(Object.class)) {
                                Morpher morpher = JSONUtils.getMorpherRegistry()
                                        .getMorpherFor(Array.newInstance(innerType, 0).getClass());
                                if (IdentityObjectMorpher.getInstance().equals(morpher)) {
                                    ObjectArrayMorpher beanMorpher = new ObjectArrayMorpher(
                                            new BeanMorpher(innerType, JSONUtils.getMorpherRegistry()));
                                    JSONUtils.getMorpherRegistry().registerMorpher(beanMorpher);
                                }
                                array = JSONUtils.getMorpherRegistry()
                                        .morph(Array.newInstance(innerType, 0).getClass(), array);
                            }
                        }
                        setProperty(root, key, array, jsonConfig);
                    }
                } else if (String.class.isAssignableFrom(type) || JSONUtils.isBoolean(type)
                        || JSONUtils.isNumber(type) || JSONUtils.isString(type)
                        || JSONFunction.class.isAssignableFrom(type)) {
                    if (pd != null) {
                        if (jsonConfig.isHandleJettisonEmptyElement() && "".equals(value)) {
                            setProperty(root, key, null, jsonConfig);
                        } else if (!pd.getPropertyType().isInstance(value)) {
                            Morpher morpher = JSONUtils.getMorpherRegistry()
                                    .getMorpherFor(pd.getPropertyType());
                            if (IdentityObjectMorpher.getInstance().equals(morpher)) {
                                log.warn("Can't transform property '" + key + "' from " + type.getName()
                                        + " into " + pd.getPropertyType().getName()
                                        + ". Will register a default BeanMorpher");
                                JSONUtils.getMorpherRegistry().registerMorpher(
                                        new BeanMorpher(pd.getPropertyType(), JSONUtils.getMorpherRegistry()));
                            }
                            setProperty(root, key,
                                    JSONUtils.getMorpherRegistry().morph(pd.getPropertyType(), value),
                                    jsonConfig);
                        } else {
                            setProperty(root, key, value, jsonConfig);
                        }
                    } else if (root instanceof Map) {
                        setProperty(root, key, value, jsonConfig);
                    } else {
                        log.warn("Tried to assign property " + key + ":" + type.getName() + " to bean of class "
                                + root.getClass().getName());
                    }
                } else {
                    if (pd != null) {
                        Class targetClass = pd.getPropertyType();
                        if (jsonConfig.isHandleJettisonSingleElementArray()) {
                            JSONArray array = new JSONArray().element(value, jsonConfig);
                            Class newTargetClass = findTargetClass(key, classMap);
                            newTargetClass = newTargetClass == null ? findTargetClass(name, classMap)
                                    : newTargetClass;
                            Object newRoot = jsonConfig.getNewBeanInstanceStrategy().newInstance(newTargetClass,
                                    null);
                            if (targetClass.isArray()) {
                                setProperty(root, key, JSONArray.toArray(array, newRoot, jsonConfig),
                                        jsonConfig);
                            } else if (Collection.class.isAssignableFrom(targetClass)) {
                                setProperty(root, key, JSONArray.toList(array, newRoot, jsonConfig),
                                        jsonConfig);
                            } else if (JSONArray.class.isAssignableFrom(targetClass)) {
                                setProperty(root, key, array, jsonConfig);
                            } else {
                                setProperty(root, key, toBean((JSONObject) value, newRoot, jsonConfig),
                                        jsonConfig);
                            }
                        } else {
                            if (targetClass == Object.class) {
                                targetClass = findTargetClass(key, classMap);
                                targetClass = targetClass == null ? findTargetClass(name, classMap)
                                        : targetClass;
                            }
                            Object newRoot = jsonConfig.getNewBeanInstanceStrategy().newInstance(targetClass,
                                    null);
                            setProperty(root, key, toBean((JSONObject) value, newRoot, jsonConfig), jsonConfig);
                        }
                    } else if (root instanceof Map) {
                        Class targetClass = findTargetClass(key, classMap);
                        targetClass = targetClass == null ? findTargetClass(name, classMap) : targetClass;
                        Object newRoot = jsonConfig.getNewBeanInstanceStrategy().newInstance(targetClass, null);
                        setProperty(root, key, toBean((JSONObject) value, newRoot, jsonConfig), jsonConfig);
                    } else {
                        log.warn("Tried to assign property " + key + ":" + type.getName() + " to bean of class "
                                + rootClass.getName());
                    }
                }
            } else {
                if (type.isPrimitive()) {
                    // assume assigned default value
                    log.warn("Tried to assign null value to " + key + ":" + type.getName());
                    setProperty(root, key, JSONUtils.getMorpherRegistry().morph(type, null), jsonConfig);
                } else {
                    setProperty(root, key, null, jsonConfig);
                }
            }
        } catch (JSONException jsone) {
            throw jsone;
        } catch (Exception e) {
            throw new JSONException("Error while setting property=" + name + " type " + type, e);
        }
    }

    return root;
}

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;
    }/*  ww w.j  a va  2  s  . co  m*/
    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;
}