Example usage for org.springframework.beans BeanWrapper getPropertyDescriptors

List of usage examples for org.springframework.beans BeanWrapper getPropertyDescriptors

Introduction

In this page you can find the example usage for org.springframework.beans BeanWrapper getPropertyDescriptors.

Prototype

PropertyDescriptor[] getPropertyDescriptors();

Source Link

Document

Obtain the PropertyDescriptors for the wrapped object (as determined by standard JavaBeans introspection).

Usage

From source file:net.solarnetwork.util.ClassUtils.java

/**
 * Get a Map of non-null bean properties for an object.
 * //from  w w  w  . ja va2  s  . co  m
 * @param o the object to inspect
 * @param ignore a set of property names to ignore (optional)
 * @return Map (never null)
 */
public static Map<String, Object> getBeanProperties(Object o, Set<String> ignore) {
    if (ignore == null) {
        ignore = DEFAULT_BEAN_PROP_NAME_IGNORE;
    }
    Map<String, Object> result = new LinkedHashMap<String, Object>();
    BeanWrapper bean = PropertyAccessorFactory.forBeanPropertyAccess(o);
    PropertyDescriptor[] props = bean.getPropertyDescriptors();
    for (PropertyDescriptor prop : props) {
        if (prop.getReadMethod() == null) {
            continue;
        }
        String propName = prop.getName();
        if (ignore != null && ignore.contains(propName)) {
            continue;
        }
        Object propValue = bean.getPropertyValue(propName);
        if (propValue == null) {
            continue;
        }
        result.put(propName, propValue);
    }
    return result;
}

From source file:net.solarnetwork.util.ClassUtils.java

/**
 * Get a Map of non-null bean properties for an object.
 * //from   ww w. j av a  2 s .c  o m
 * @param o the object to inspect
 * @param ignore a set of property names to ignore (optional)
 * @param serializeIgnore if <em>true</em> test for the {@link SerializeIgnore}
 * annotation for ignoring properties
 * @return Map (never null)
 */
public static Map<String, Object> getBeanProperties(Object o, Set<String> ignore, boolean serializeIgnore) {
    if (o == null) {
        return null;
    }
    if (ignore == null) {
        ignore = DEFAULT_BEAN_PROP_NAME_IGNORE;
    }
    Map<String, Object> result = new LinkedHashMap<String, Object>();
    BeanWrapper bean = PropertyAccessorFactory.forBeanPropertyAccess(o);
    PropertyDescriptor[] props = bean.getPropertyDescriptors();
    for (PropertyDescriptor prop : props) {
        if (prop.getReadMethod() == null) {
            continue;
        }
        String propName = prop.getName();
        if (ignore != null && ignore.contains(propName)) {
            continue;
        }
        Object propValue = bean.getPropertyValue(propName);
        if (propValue == null) {
            continue;
        }
        if (serializeIgnore) {
            Method getter = prop.getReadMethod();
            if (getter != null && getter.isAnnotationPresent(SerializeIgnore.class)) {
                continue;
            }
        }
        result.put(propName, propValue);
    }
    return result;
}

From source file:net.solarnetwork.util.ClassUtils.java

/**
 * Copy non-null bean properties from one object to another.
 * /*  ww  w  .  ja v a2s  .c  om*/
 * @param src the object to copy values from
 * @param dest the object to copy values to
 * @param ignore a set of property names to ignore (optional)
 * @param emptyStringToNull if <em>true</em> then String values that 
 * are empty or contain only whitespace will be treated as if they
 * where <em>null</em>
 */
public static void copyBeanProperties(Object src, Object dest, Set<String> ignore, boolean emptyStringToNull) {
    if (ignore == null) {
        ignore = DEFAULT_BEAN_PROP_NAME_IGNORE;
    }
    BeanWrapper bean = PropertyAccessorFactory.forBeanPropertyAccess(src);
    BeanWrapper to = PropertyAccessorFactory.forBeanPropertyAccess(dest);
    PropertyDescriptor[] props = bean.getPropertyDescriptors();
    for (PropertyDescriptor prop : props) {
        if (prop.getReadMethod() == null) {
            continue;
        }
        String propName = prop.getName();
        if (ignore != null && ignore.contains(propName)) {
            continue;
        }
        Object propValue = bean.getPropertyValue(propName);
        if (propValue == null || (emptyStringToNull && (propValue instanceof String)
                && !StringUtils.hasText((String) propValue))) {
            continue;
        }
        if (to.isWritableProperty(propName)) {
            to.setPropertyValue(propName, propValue);
        }
    }
}

From source file:com.taobao.rpc.doclet.RPCAPIInfoHelper.java

/**
 * ?//ww  w. j ava 2 s .c om
 * 
 * @param method
 * @return
 */
public static Object buildTypeStructure(Class<?> type, Type genericType, Type oriGenericType) {
    if ("void".equalsIgnoreCase(type.getName()) || ClassUtils.isPrimitiveOrWrapper(type)
            || String.class.isAssignableFrom(type) || Date.class.isAssignableFrom(type)
            || URL.class.isAssignableFrom(type)) {
        // 
        return type.getName().replaceAll("java.lang.", "").replaceAll("java.util.", "").replaceAll("java.sql.",
                "");
    } // end if

    if (type.isArray()) {
        // 
        return new Object[] {
                buildTypeStructure(type.getComponentType(), type.getComponentType(), genericType) };
    } // end if

    if (ClassUtils.isAssignable(Map.class, type)) {
        // Map
        return Map.class.getName();
    } // end if

    if (type.isEnum()) {
        // Enum
        return Enum.class.getName();
    } // end if

    boolean isCollection = type != null ? Collection.class.isAssignableFrom(type) : false;

    if (isCollection) {

        Type rawType = type;
        if (genericType != null) {
            if (genericType instanceof ParameterizedType) {
                ParameterizedType _type = (ParameterizedType) genericType;
                Type[] actualTypeArguments = _type.getActualTypeArguments();
                rawType = actualTypeArguments[0];

            } else if (genericType instanceof GenericArrayType) {
                rawType = ((GenericArrayType) genericType).getGenericComponentType();
            }

            if (genericType instanceof WildcardType) {
                rawType = ((WildcardType) genericType).getUpperBounds()[0];
            }
        }

        if (rawType == type) {

            return new Object[] { rawType.getClass().getName() };
        } else {

            if (rawType.getClass().isAssignableFrom(TypeVariableImpl.class)) {
                return new Object[] { buildTypeStructure(
                        (Class<?>) ((ParameterizedType) oriGenericType).getActualTypeArguments()[0], rawType,
                        genericType) };
            } else {
                if (rawType instanceof ParameterizedType) {
                    if (((ParameterizedType) rawType).getRawType() == Map.class) {
                        return new Object[] { Map.class.getName() };
                    }
                }
                if (oriGenericType == rawType) {
                    return new Object[] { rawType.getClass().getName() };
                }
                return new Object[] { buildTypeStructure((Class<?>) rawType, rawType, genericType) };
            }
        }
    }

    if (type.isInterface()) {
        return type.getName();
    }

    ClassInfo paramClassInfo = RPCAPIDocletUtil.getClassInfo(type.getName());
    //added 
    if (null == paramClassInfo) {
        System.out.println("failed to get paramClassInfo for :" + type.getName());
        return null;
    }

    List<FieldInfo> typeConstructure = new ArrayList<FieldInfo>();

    BeanWrapper bean = new BeanWrapperImpl(type);

    PropertyDescriptor[] propertyDescriptors = bean.getPropertyDescriptors();
    Method readMethod;

    String name;

    for (PropertyDescriptor propertyDescriptor : propertyDescriptors) {
        readMethod = propertyDescriptor.getReadMethod();

        if (readMethod == null || "getClass".equals(readMethod.getName())) {
            continue;
        }

        name = propertyDescriptor.getName();

        FieldInfo fieldInfo = paramClassInfo.getFieldInfo(name);
        if (readMethod.getReturnType().isAssignableFrom(type)) {
            String comment = "structure is the same with parent.";
            typeConstructure
                    .add(FieldInfo.create(name, fieldInfo != null ? fieldInfo.getComment() : "", comment));
        } else {
            typeConstructure.add(
                    FieldInfo.create(name, fieldInfo != null ? fieldInfo.getComment() : "", buildTypeStructure(
                            readMethod.getReturnType(), readMethod.getGenericReturnType(), genericType)));
        } // end if
    }

    return typeConstructure;
}

From source file:net.kamhon.ieagle.util.ReflectionUtil.java

/**
 * search String variavle inside the given object, if Empty then change it to Null.
 * //from  ww  w.j ava2s . c om
 * @param obj
 *            = this object will not be changed, it will be close.
 * @return
 */
public static Object changeEmptyStrToNull(Object obj) {
    Object newObj = obj;
    // J.printLine(getAllExProperties(obj, " ", ".vo."));
    // try {
    // newObj = BeanUtils.cloneBean(obj);
    // } catch (Exception e1) {
    // e1.printStackTrace();
    // }
    //
    BeanWrapper beanO1 = new BeanWrapperImpl(newObj);
    PropertyDescriptor[] proDescriptorsO1 = beanO1.getPropertyDescriptors();
    int propertyLength = proDescriptorsO1.length;

    for (int i = 0; i < propertyLength; i++) {
        try {
            Object propertyValueO1 = beanO1.getPropertyValue(proDescriptorsO1[i].getName());
            if (propertyValueO1 instanceof String && StringUtils.isEmpty((String) propertyValueO1)) {
                // password is null. it will not come in because it is not
                // instance of String
                // J.printNegetif(proDescriptorsO1[i].getName()+"..."+(String)propertyValueO1);
                beanO1.setPropertyValue(proDescriptorsO1[i].getName(), null);

            }
        } catch (Exception e) {
            // [exec] java.lang.IllegalAccessException: Class
            // org.apache.commons.beanutils.BeanUtilsBean can not
            // access a member of class
            // com.foremobile.gateway.usermgmt.vo.User with modifiers
            // "private"
            // [exec] at sun.reflect.Reflection.ensureMemberAccess(Unknown
            // Source)
        }
    }

    return newObj;
}

From source file:net.kamhon.ieagle.util.ReflectionUtil.java

/**
 * //www  .j  av  a2 s .  c  o  m
 * get all properties and it value which is public method which name get* if obj is collection->no browser in the
 * collection. only go in object in objPath package. Other than that just get the value and no go in to it
 * preperties.
 * 
 * @param obj
 *            = object that needed to print all the properties.
 * @param objIndicator
 *            = other object indication when vo contain other vo.
 * @param objPath
 *            = only browse object which class path contain objPath string.
 * @return
 */
private static StringBuilder getAllProperties(Object obj, String objIndicator, String objPath) {

    StringBuilder retAllPreperties = new StringBuilder();
    try {
        retAllPreperties.append("\n" + objIndicator + obj + "->");

        BeanWrapper beanO1 = new BeanWrapperImpl(obj);
        PropertyDescriptor[] proDescriptorsO1 = beanO1.getPropertyDescriptors();
        int propertyLength = proDescriptorsO1.length;
        for (int i = 0; i < propertyLength; i++) {
            String variable = proDescriptorsO1[i].getName();
            // String clazz =
            // proDescriptorsO1[i].getPropertyType().toString();
            try {
                Object propertyValueO1 = beanO1.getPropertyValue(variable);
                // compare whether it is vo. if not just print prepertie
                // else go in

                // if (propertyValueO1 == null){
                //
                // continue;
                //
                // // go in vo
                // }else if (propertyValueO1 instanceof Collection){
                // Collection collection = (Collection)propertyValueO1;
                // if (!collection.isEmpty()){
                // collection.toArray()[0].getClass();
                // }
                // }

                if (propertyValueO1 == null) {
                    retAllPreperties.append(variable + "=" + propertyValueO1 + ";");

                    // /** for Set/List **/
                    // }else if (propertyValueO1 instanceof Collection){
                    // Collection collection = (Collection)propertyValueO1;
                    // if (CollectionUtil.isNotEmpty(collection))
                    // for(Object obj2 : collection){
                    // getAllProperties(obj2,
                    // objIndicator + objIndicator,objPath);
                    // }
                } else if (propertyValueO1.getClass().toString().contains(objPath)) {

                    retAllPreperties
                            .append(getAllProperties(propertyValueO1, objIndicator + objIndicator, objPath));
                    retAllPreperties.append("\n" + objIndicator);
                } else {

                    retAllPreperties.append(variable + "=" + propertyValueO1 + ";");
                }
            } catch (Exception e) {

            }
        }
    } catch (Exception e) {

    }
    return retAllPreperties;
}

From source file:org.codehaus.griffon.commons.GriffonClassUtils.java

/**
 * Retrieves a PropertyDescriptor for the specified instance and property value
 *
 * @param instance The instance//from w  w  w  .  j  av  a2 s.c  o m
 * @param propertyValue The value of the property
 * @return The PropertyDescriptor
 */
public static PropertyDescriptor getPropertyDescriptorForValue(Object instance, Object propertyValue) {
    if (instance == null || propertyValue == null)
        return null;

    BeanWrapper wrapper = new BeanWrapperImpl(instance);
    PropertyDescriptor[] descriptors = wrapper.getPropertyDescriptors();

    for (int i = 0; i < descriptors.length; i++) {
        Object value = wrapper.getPropertyValue(descriptors[i].getName());
        if (propertyValue.equals(value))
            return descriptors[i];
    }
    return null;
}

From source file:org.codehaus.griffon.commons.GriffonClassUtils.java

/**
 * Retrieves all the properties of the given class for the given type
 *
 * @param clazz The class to retrieve the properties from
 * @param propertyType The type of the properties you wish to retrieve
 *
 * @return An array of PropertyDescriptor instances
 *///from  www.  j ava  2s  .  c  om
public static PropertyDescriptor[] getPropertiesOfType(Class clazz, Class propertyType) {
    if (clazz == null || propertyType == null)
        return new PropertyDescriptor[0];

    Set properties = new HashSet();
    try {
        BeanWrapper wrapper = new BeanWrapperImpl(clazz.newInstance());
        PropertyDescriptor[] descriptors = wrapper.getPropertyDescriptors();

        for (int i = 0; i < descriptors.length; i++) {
            Class currentPropertyType = descriptors[i].getPropertyType();
            if (isTypeInstanceOfPropertyType(propertyType, currentPropertyType)) {
                properties.add(descriptors[i]);
            }
        }

    } catch (Exception e) {
        // if there are any errors in instantiating just return null for the moment
        return new PropertyDescriptor[0];
    }
    return (PropertyDescriptor[]) properties.toArray(new PropertyDescriptor[properties.size()]);
}

From source file:org.gageot.excel.beans.BeanSetterImpl.java

/**
 * Set the value of a property on the current bean.
 * //  w ww . j a  v a  2  s. c  o m
 * @param bean bean instance to populate
 * @param propertyName the name of the property (case insensitive)
 * @param propertyValue the value of the property
 */
@Override
public void setProperty(Object bean, String propertyName, Object propertyValue) throws BeansException {
    BeanWrapper wrapper = getWrapper(bean);

    PropertyDescriptor[] propertyDescriptors = wrapper.getPropertyDescriptors();

    // Find a bean property by its name ignoring case.
    // this way, we can accept any type of case in the spreadsheet file
    //
    for (PropertyDescriptor propertyDescriptor : propertyDescriptors) {
        if (propertyDescriptor.getName().equalsIgnoreCase(propertyName)) {
            wrapper.setPropertyValue(propertyDescriptor.getName(), propertyValue.toString());
            break;
        }
    }
}

From source file:ru.ilb.common.jpa.tools.DescriptorUtils.java

public void fixInverseLinks(Object entity) {
    final BeanWrapper src = new BeanWrapperImpl(entity);
    java.beans.PropertyDescriptor[] pds = src.getPropertyDescriptors();
    ClassDescriptor cd = entityManager.unwrap(Session.class).getDescriptor(entity);
    if (cd == null) {
        return;/*w  w w . j  ava  2s.co m*/
    }
    for (java.beans.PropertyDescriptor pd : pds) {
        DatabaseMapping dm = cd.getMappingForAttributeName(pd.getName());
        if (dm != null) {
            if (dm instanceof OneToManyMapping) {
                OneToManyMapping dmOtM = (OneToManyMapping) dm;
                if (dmOtM.getMappedBy() != null) {
                    List srcValue = (List) src.getPropertyValue(pd.getName());
                    if (srcValue != null) {
                        for (Object v : srcValue) {
                            final BeanWrapper srcv = new BeanWrapperImpl(v);
                            srcv.setPropertyValue(dmOtM.getMappedBy(), entity);
                            fixInverseLinks(v);
                        }
                    }

                }
            }
            if (dm instanceof OneToOneMapping) {
                OneToOneMapping dmOtO = (OneToOneMapping) dm;
                if (dmOtO.getMappedBy() != null) {
                    Object srcValue = src.getPropertyValue(pd.getName());
                    if (srcValue != null) {
                        final BeanWrapper srcv = new BeanWrapperImpl(srcValue);
                        srcv.setPropertyValue(dmOtO.getMappedBy(), entity);
                        fixInverseLinks(srcValue);
                    }

                }
            }
        }

    }
}