Example usage for java.beans PropertyDescriptor getReadMethod

List of usage examples for java.beans PropertyDescriptor getReadMethod

Introduction

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

Prototype

public synchronized Method getReadMethod() 

Source Link

Document

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

Usage

From source file:org.caratarse.auth.model.util.BeanUtils.java

/**
 * Copy the not-null property values of the given source bean into the given target bean.
 * <p>//from www . java 2  s  . c o  m
 * 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
 * @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 copyNotNullProperties(Object source, Object target, Class<?> editable,
        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 = org.springframework.beans.BeanUtils.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 = org.springframework.beans.BeanUtils
                    .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 (value == null) {
                            continue;
                        }
                        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:kelly.util.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// ww  w.  j  a  va2 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, Class<?> editable,
        String... ignoreProperties) {

    Validate.notNull(source, "Source must not be null");
    Validate.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 && (ignoreProperties == null || (!ignoreList.contains(targetPd.getName())))) {
            PropertyDescriptor sourcePd = getPropertyDescriptor(source.getClass(), targetPd.getName());
            if (sourcePd != null) {
                Method readMethod = sourcePd.getReadMethod();
                if (readMethod != null
                        && writeMethod.getParameterTypes()[0].isAssignableFrom(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 BeanException(
                                "Could not copy property '" + targetPd.getName() + "' from source to target",
                                ex);
                    }
                }
            }
        }
    }
}

From source file:org.apache.activemq.artemis.tests.integration.jms.connection.ConnectionFactorySerializationTest.java

private static void checkEquals(Object factory, Object factory2)
        throws IllegalAccessException, InvocationTargetException, NoSuchMethodException {
    BeanUtilsBean bean = new BeanUtilsBean();
    PropertyDescriptor[] descriptors = bean.getPropertyUtils().getPropertyDescriptors(factory);
    for (PropertyDescriptor descriptor : descriptors) {
        if (descriptor.getWriteMethod() != null && descriptor.getReadMethod() != null) {
            Assert.assertEquals(descriptor.getName() + " incorrect",
                    bean.getProperty(factory, descriptor.getName()),
                    bean.getProperty(factory2, descriptor.getName()));
        }/*from  w  w  w  . j a  v a2 s.  c  o  m*/
    }
}

From source file:org.jaffa.qm.util.PropertyFilter.java

private static void getFieldList(Class clazz, List<String> fieldList, String prefix, Deque<Class> classStack)
        throws IntrospectionException {
    //To avoid recursion, bail out if the input Class has already been introspected
    if (classStack.contains(clazz)) {
        if (log.isDebugEnabled())
            log.debug("Fields from " + clazz + " prefixed by " + prefix
                    + " will be ignored, since the class has already been introspected as per the stack "
                    + classStack);/*from  ww  w.  j av a2 s.c om*/
        return;
    } else
        classStack.addFirst(clazz);

    //Introspect the input Class
    BeanInfo beanInfo = Introspector.getBeanInfo(clazz);
    if (beanInfo != null) {
        PropertyDescriptor[] pds = beanInfo.getPropertyDescriptors();
        if (pds != null) {
            for (PropertyDescriptor pd : pds) {
                if (pd.getReadMethod() != null && pd.getWriteMethod() != null) {
                    String name = pd.getName();
                    String qualifieldName = prefix == null || prefix.length() == 0 ? name : prefix + '.' + name;
                    Class type = pd.getPropertyType();
                    if (type.isArray())
                        type = type.getComponentType();
                    if (type == String.class || type == Boolean.class || Number.class.isAssignableFrom(type)
                            || IDateBase.class.isAssignableFrom(type) || Currency.class.isAssignableFrom(type)
                            || type.isPrimitive() || type.isEnum())
                        fieldList.add(qualifieldName);
                    else
                        getFieldList(type, fieldList, qualifieldName, classStack);
                }
            }
        }
    }

    classStack.removeFirst();
}

From source file:com.espertech.esper.event.bean.PropertyHelper.java

/**
 * Adds to the given list of property descriptors the properties of the given class
 * using the Introspector to introspect properties. This also finds array and indexed properties.
 * @param clazz to introspect/*www  .j a  v  a2 s.  c  o m*/
 * @param result is the list to add to
 */
protected static void addIntrospectProperties(Class clazz, List<InternalEventPropDescriptor> result) {
    PropertyDescriptor properties[] = introspect(clazz);
    for (int i = 0; i < properties.length; i++) {
        PropertyDescriptor property = properties[i];
        String propertyName = property.getName();
        Method readMethod = property.getReadMethod();

        EventPropertyType type = EventPropertyType.SIMPLE;
        if (property instanceof IndexedPropertyDescriptor) {
            readMethod = ((IndexedPropertyDescriptor) property).getIndexedReadMethod();
            type = EventPropertyType.INDEXED;
        }

        if (readMethod == null) {
            continue;
        }

        result.add(new InternalEventPropDescriptor(propertyName, readMethod, type));
    }
}

From source file:it.sample.parser.util.CommonsUtil.java

/**
 * Metodo di utilita' per rendere null un'istanza di una classe che e' istanziata ma che ha tutti i campi null
 * /*from  ww  w . j  a v  a2  s.  co  m*/
 * @param instance
 */
public static <T> void sanitizeObject(T instance) {
    PropertyDescriptor[] descriptors = PropertyUtils.getPropertyDescriptors(instance);
    if (descriptors != null) {
        for (PropertyDescriptor descriptor : descriptors) {
            try {
                String propertyName = descriptor.getName();
                if (descriptor.getReadMethod() != null) {
                    Object val = PropertyUtils.getProperty(instance, propertyName);
                    if (val != null && !BeanUtils.isSimpleProperty(val.getClass())
                            && descriptor.getWriteMethod() != null && !isFilled(val)
                            && !val.getClass().getName().startsWith("java.util")) {
                        PropertyUtils.setProperty(instance, propertyName, null);
                    }
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
}

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.j a v  a 2s  .  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:grails.plugin.searchable.internal.SearchableUtils.java

/**
 * If the given domain class property is a generic collection, this method
 * returns the element type of that collection. Otherwise, it returns
 * <code>null</code>./*from w w w  . j a v a  2 s  .com*/
 */
public static Class getElementClass(GrailsDomainClassProperty property) {
    PropertyDescriptor descriptor = BeanUtils.getPropertyDescriptor(property.getDomainClass().getClazz(),
            property.getName());
    Type type = descriptor.getReadMethod().getGenericReturnType();
    if (type instanceof ParameterizedType) {
        for (Type argType : ((ParameterizedType) type).getActualTypeArguments()) {
            return (Class) argType;
        }
    }

    return null;
}

From source file:jp.primecloud.auto.util.StringUtils.java

public static String reflectToString(Object object) {
    if (object == null) {
        return null;
    }/*from   w ww.j a  va 2s .  c o m*/

    // String??
    if (object instanceof String) {
        return (String) object;
    }

    // ??
    if (object instanceof Number) {
        return object.toString();
    }

    // Boolean??
    if (object instanceof Boolean) {
        return object.toString();
    }

    // Character??
    if (object instanceof Character) {
        return object.toString();
    }

    // ???
    if (object instanceof Object[]) {
        return reflectToString(Arrays.asList((Object[]) object));
    }

    // ??
    if (object instanceof Collection<?>) {
        Iterator<?> iterator = ((Collection<?>) object).iterator();
        if (!iterator.hasNext()) {
            return "[]";
        }

        StringBuilder str = new StringBuilder();
        str.append("[");
        while (true) {
            Object object2 = iterator.next();
            str.append(reflectToString(object2));
            if (!iterator.hasNext()) {
                break;
            }
            str.append(", ");
        }
        str.append("]");
        return str.toString();
    }

    // ??
    if (object instanceof Map<?, ?>) {
        Iterator<?> iterator = ((Map<?, ?>) object).entrySet().iterator();
        if (!iterator.hasNext()) {
            return "{}";
        }

        StringBuilder str = new StringBuilder();
        str.append("{");
        while (true) {
            Object entry = iterator.next();
            str.append(reflectToString(entry));
            if (!iterator.hasNext()) {
                break;
            }
            str.append(", ");
        }
        str.append("}");
        return str.toString();
    }

    // Entry??
    if (object instanceof Entry<?, ?>) {
        Entry<?, ?> entry = (Entry<?, ?>) object;
        StringBuilder str = new StringBuilder();
        str.append(reflectToString(entry.getKey()));
        str.append("=");
        str.append(reflectToString(entry.getValue()));
        return str.toString();
    }

    // toString?????
    try {
        Method method = object.getClass().getMethod("toString");
        if (!Object.class.equals(method.getDeclaringClass())) {
            return object.toString();
        }
    } catch (NoSuchMethodException ignore) {
    }

    // ?????
    try {
        PropertyDescriptor[] descriptors = Introspector.getBeanInfo(object.getClass()).getPropertyDescriptors();
        StringBuilder str = new StringBuilder();
        str.append("[");
        for (PropertyDescriptor descriptor : descriptors) {
            if ("class".equals(descriptor.getName())) {
                continue;
            }

            Method readMethod = descriptor.getReadMethod();
            if (readMethod == null) {
                continue;
            }

            if (str.length() > 1) {
                str.append(", ");
            }
            Object object2 = readMethod.invoke(object);
            str.append(descriptor.getName()).append("=").append(reflectToString(object2));
        }
        str.append("]");
        return str.toString();
    } catch (IntrospectionException ignore) {
    } catch (InvocationTargetException ignore) {
    } catch (IllegalAccessException ignore) {
    }

    // ????????commons-lang?
    return ReflectionToStringBuilder.toString(object);
}

From source file:net.mojodna.searchable.util.SearchableUtils.java

/**
 * @param clazz/*from   w ww .jav a2 s.  c  o  m*/
 * @param propertyName
 * @return Return type.
 */
public static final Class<?> getReturnType(final Class<?> clazz, final String propertyName) {
    final String key = clazz.getName() + "#" + propertyName;

    if (returnTypeCache.containsKey(key)) {
        return returnTypeCache.get(key);
    }

    if (returnTypeMissCache.containsKey(key)) {
        return null;
    }

    for (final PropertyDescriptor d : PropertyUtils.getPropertyDescriptors(clazz)) {
        if (d.getName().equals(propertyName)) {
            final Class<?> returnType = d.getReadMethod().getReturnType();
            returnTypeCache.put(key, returnType);
            return returnType;
        }
    }

    returnTypeMissCache.put(key, key);
    return null;
}