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:cn.fql.utility.ClassUtility.java

/**
 * Import data to this object from input Map
 *
 * @param obj    object/*w w w  . jav a  2 s . co m*/
 * @param values <code>values</code>
 */
public static void importValueFromMap(Object obj, Map values) {
    if (values != null) {
        PropertyDescriptor[] pds;
        try {
            pds = exportPropertyDesc(obj.getClass());
            if (pds != null && pds.length > 0) {
                Set keySet = values.keySet();
                Iterator it = keySet.iterator();
                while (it.hasNext()) {
                    String name = (String) it.next();
                    for (int i = 0; i < pds.length; i++) {
                        PropertyDescriptor pd = pds[i];
                        if (pd.getName().equals(name)) {
                            Method setter = pd.getWriteMethod();
                            if (setter != null) {
                                Object[] params = { values.get(name) };
                                setter.invoke(obj, params);
                            }
                            break;
                        }
                    }
                }
            }
        } catch (Exception e) {
            System.out.println(e.getMessage());
        }
    }
}

From source file:nl.strohalm.cyclos.utils.database.DatabaseHelper.java

/**
 * Returns a set of properties that will be fetched directly on the HQL
 *///from  w w  w .  ja  va  2 s .  co  m
private static Set<String> getDirectRelationshipProperties(final Class<? extends Entity> entityType,
        final Collection<Relationship> fetch) {
    // Populate the direct properties cache for this entity if not yet exists
    Set<String> cachedDirectProperties = directPropertiesCache.get(entityType);
    if (cachedDirectProperties == null) {
        cachedDirectProperties = new HashSet<String>();
        final PropertyDescriptor[] propertyDescriptors = PropertyUtils.getPropertyDescriptors(entityType);
        // Scan for child -> parent relationships
        for (final PropertyDescriptor descriptor : propertyDescriptors) {
            if (descriptor.getReadMethod() != null && descriptor.getWriteMethod() != null
                    && Entity.class.isAssignableFrom(descriptor.getPropertyType())) {
                // This is a child -> parent relationship. Add it to the cache
                cachedDirectProperties.add(descriptor.getName());
            }
        }
        directPropertiesCache.put(entityType, cachedDirectProperties);
    }

    // Build the properties to add to HQL fetch from a given relationship set
    final Set<String> propertiesToAddToFetch = new HashSet<String>();
    for (final Relationship relationship : fetch) {
        final String name = PropertyHelper.firstProperty(relationship.getName());
        if (cachedDirectProperties.contains(name)) {
            propertiesToAddToFetch.add(name);
        }
    }
    return propertiesToAddToFetch;
}

From source file:org.openempi.webapp.server.util.BaseModelDataDtoGenerator.java

private static void generateGetterSetter(StringBuilder sourceCode, PropertyDescriptor desc) {
    // getter method declaration
    sourceCode.append("\tpublic ").append(desc.getPropertyType().getCanonicalName()).append(" ")
            .append(desc.getReadMethod().getName()).append("() {\n");

    // getter method body
    sourceCode.append("\t\treturn get(\"").append(desc.getName()).append("\");\n\t}\n\n");

    // setter method declaration
    sourceCode.append("\tpublic void ").append(desc.getWriteMethod().getName()).append("(")
            .append(desc.getPropertyType().getCanonicalName()).append(" ").append(desc.getName())
            .append(") {\n");

    // getter method body
    sourceCode.append("\t\tset(\"").append(desc.getName()).append("\", ").append(desc.getName())
            .append(");\n\t}\n\n");
}

From source file:net.mojodna.sprout.support.SproutUtils.java

/**
 * Bean initialization method.  Uses reflection to determine properties
 * for which auto-wiring may be appropriate.  Subsequently attempts to
 * retrieve appropriate beans from the WebApplicationContext and set them
 * locally.// w w w  .j  a  v a 2s  .c om
 * 
 * @param bean Bean to initialize.
 * @param context WebApplicationContext containing Spring beans.
 * @param clazz Type of Sprout.  This is used to determine which declared
 * methods are candidates for auto-wiring.
 */
public static void initialize(final Object bean, final WebApplicationContext context, final Class clazz) {
    final Collection<Method> methods = SproutUtils.getDeclaredMethods(bean.getClass(), clazz);

    final PropertyDescriptor[] descriptors = PropertyUtils.getPropertyDescriptors(bean.getClass());
    for (final PropertyDescriptor descriptor : descriptors) {
        final Class type = descriptor.getPropertyType();

        // beans should never be of type String
        // there must be a write method present
        // the write method must exist within the relevant subset of declared methods
        if (!type.equals(String.class) && null != descriptor.getWriteMethod()
                && methods.contains(descriptor.getWriteMethod())) {
            final Object serviceBean = context.getBean(descriptor.getName());
            if (null != serviceBean) {
                try {
                    log.debug("Wiring property '" + descriptor.getName() + "' with bean of type "
                            + serviceBean.getClass().getName());
                    PropertyUtils.setProperty(bean, descriptor.getName(), serviceBean);
                } catch (final IllegalAccessException e) {
                    throw new RuntimeException(e);
                } catch (final InvocationTargetException e) {
                    throw new RuntimeException(e);
                } catch (final NoSuchMethodException e) {
                    throw new RuntimeException(e);
                }
            }
        }
    }

    /**
     * TODO additional lifecycle interface callbacks as defined in BeanFactory
     * should be implemented here
     * @see org.springframework.beans.factory.BeanFactory
     */

    // InitializingBean callback
    if (bean instanceof InitializingBean) {
        try {
            ((InitializingBean) bean).afterPropertiesSet();
        } catch (final Exception e) {
            log.warn("Exception while running afterPropertiesSet() on an InitializingBean: " + e.getMessage(),
                    e);
        }
    }
}

From source file:org.hellojavaer.testcase.generator.TestCaseGenerator.java

@SuppressWarnings({ "rawtypes", "unchecked" })
private static <T> void checkBeanValidity(Class<T> clazz, List<String> excludeFieldList,
        int recursiveCycleLimit) {
    PropertyDescriptor[] pds = BeanUtils.getPropertyDescriptors(clazz);
    boolean validBean = false;
    for (PropertyDescriptor pd : pds) {
        if (pd.getWriteMethod() != null && pd.getReadMethod() != null && //
                (excludeFieldList != null && !excludeFieldList.contains(pd.getName())
                        || excludeFieldList == null) //
        ) {// www .j  ava 2  s  .  co  m
            validBean = true;
            // just set write ,read for user control
            if (!Modifier.isPublic(pd.getWriteMethod().getDeclaringClass().getModifiers())) {
                pd.getWriteMethod().setAccessible(true);
            }

            Class fieldClazz = pd.getPropertyType();
            if (!TypeUtil.isBaseType(fieldClazz)) {
                try {
                    // ????
                    if (recursiveCycleLimit == 0 && fieldClazz == clazz) {
                        throw new RuntimeException("recursive cycle limit is 0! field[" + pd.getName()
                                + "] may cause recursive, please add this field[" + pd.getName()
                                + "] to exclude list or set recursiveCycleLimit more than 0 .");
                    } else if (!fieldClazz.isAssignableFrom(clazz)) {
                        checkBeanValidity(fieldClazz, null, 999999999);
                    }
                } catch (Exception e) {
                    throw new RuntimeException("Unknown Class " + fieldClazz.getName() + " for field "
                            + pd.getName() + " ! please add this field[" + pd.getName() + "] to exclude list.",
                            e);
                }
            }
        }
    }
    if (!validBean) {
        throw new RuntimeException(
                "Invalid Bean Class[" + clazz.getName() + "], for it has not getter setter methods!");
    }
}

From source file:org.apache.myfaces.el.PropertyResolverImpl.java

public static void setProperty(Object base, String name, Object newValue) {
    PropertyDescriptor propertyDescriptor = getPropertyDescriptor(base, name);

    Method m = propertyDescriptor.getWriteMethod();
    if (m == null) {
        throw new PropertyNotFoundException(getMessage(base, name) + " (no write method for property!)");
    }// www  . ja  v a 2 s .c o  m

    // Check if the concrete class of this method is accessible and if not
    // search for a public interface that declares this method
    m = MethodUtils.getAccessibleMethod(m);
    if (m == null) {
        throw new PropertyNotFoundException(getMessage(base, name) + " (not accessible!)");
    }

    try {
        m.invoke(base, new Object[] { newValue });
    } catch (Throwable t) {
        log.debug("Exception while invoking setter method.", t);
        throw new EvaluationException(getMessage(base, name, newValue, m), t);
    }
}

From source file:de.iteratec.iteraplan.businesslogic.exchange.common.vbb.impl.util.VisualVariableHelper.java

private static VisualVariable getVVAnnotation(PropertyDescriptor vvCandidate) {
    VisualVariable vvAnnotation = null;//w w  w. ja  v a  2 s  . c o  m
    if (vvCandidate.getReadMethod() != null) {
        vvAnnotation = AnnotationUtils.findAnnotation(vvCandidate.getReadMethod(), VisualVariable.class);
    }
    if (vvAnnotation == null && vvCandidate.getWriteMethod() != null) {
        vvAnnotation = AnnotationUtils.findAnnotation(vvCandidate.getWriteMethod(), VisualVariable.class);
    }
    return vvAnnotation;
}

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

/**
 *
 * @param clazz/* w  w  w.ja  v  a 2s.  c om*/
 * @param propertyName El nombre de la propiedad permite que sean varias
 * "nested" con puntos. Ej: "prop1.prop2.prop3"
 * @return
 */
static public boolean existsWritePropertyInClass(Class clazz, String propertyName) {
    PropertyDescriptor propertyDescriptor = getPropertyDescriptor(clazz, propertyName);

    if (propertyDescriptor.getWriteMethod() != null) {
        return true;
    } else {
        return false;
    }
}

From source file:org.zht.framework.util.ZBeanUtil.java

@SuppressWarnings("rawtypes")
public static Object convertMapToBean(Map map, Class<?> type) {
    Object obj = null;//from   w w w  .ja va  2  s.c o  m
    try {
        BeanInfo beanInfo = null;

        beanInfo = Introspector.getBeanInfo(type);
        obj = type.newInstance();
        PropertyDescriptor[] propertyDescriptors = beanInfo.getPropertyDescriptors();
        for (PropertyDescriptor property : propertyDescriptors) {
            String properName = property.getName();
            if (map.containsKey(property.getName())) {
                try {// ??

                    Object value = map.get(properName);
                    Method setter = property.getWriteMethod();
                    setter.invoke(obj, value);
                    //Unable to find non-private method
                    //               access.invoke(obj,"set" + ZStrUtil.toUpCaseFirst(properName),value);
                } catch (Exception e) {
                    e.printStackTrace();
                }

            }
        }
    } catch (Exception e) {
        e.printStackTrace();
        return obj;
    }
    return obj;
}

From source file:com.ksmpartners.ernie.util.TestUtil.java

/**
 * Test setter and getter call and make sure they match.
 * <p>//from w  w  w . ja  v  a2  s  .c  o  m
 * @param property the property to be set
 * @param setValue the value to be set
 * @param qName qualified name for error reporting
 */
private static void testProperty(Object target, PropertyDescriptor property, Object setValue, String qName) {

    // flag indicating whether a comparison should be done at the end
    boolean expectMatch = true;

    // call setter (if exists)
    if (property.getWriteMethod() != null) {
        invokeMethod(target, property.getWriteMethod(), new Object[] { setValue }, qName);
    } else {
        Assert.assertFalse(true, "Property " + qName + " does not have the required setter.");
        expectMatch = false;
    }

    // call getter (if exists)
    Object getValue = null;
    if (property.getReadMethod() != null) {
        getValue = invokeMethod(target, property.getReadMethod(), null, qName);
    } else {
        Assert.assertFalse(true, "Property " + qName + " does not have the required getter.");
        expectMatch = false;
    }

    // if expecting a match, compare
    // if they are not the same instance, assert that they have equality
    if (expectMatch && setValue != getValue)
        Assert.assertEquals(getValue, setValue,
                "Values did not match for getter/setter call on field " + qName);
}