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:gr.interamerican.bo2.utils.JavaBeanUtils.java

/**
 * Gets the value of a property on an object.
 * //from  w  ww  .j ava  2s . c  o  m
 * If the property has a getter method, then it will be called.
 * If the property does not have a getter method, the field
 * will be get. If there is no such field, then a RuntimeException
 * with cause a NoSuchFieldException will be thrown. <br/>
 * The method will box any {@link Exception} thrown during java reflection
 * calls inside a {@link RuntimeException}.
 * 
 * @param pd
 *            Descriptor of the property.
 * @param obj
 *            Object on which the property is accessed.
 *            
 * @return Returns the value of this property.
 */
public static Object getProperty(PropertyDescriptor pd, Object obj) {
    Method getter = pd.getReadMethod();
    if (getter != null) {
        return ReflectionUtils.invoke(getter, obj);
    } else {
        String fieldName = pd.getName();
        try {
            Field field = obj.getClass().getDeclaredField(fieldName);
            field.setAccessible(true);
            return ReflectionUtils.get(field, obj);
        } catch (NoSuchFieldException nse) {
            throw new RuntimeException(nse);
        }
    }
}

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

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

From source file:org.apache.syncope.core.misc.jexl.JexlUtils.java

public static JexlContext addFieldsToContext(final Object object, final JexlContext jexlContext) {
    JexlContext context = jexlContext == null ? new MapContext() : jexlContext;

    try {// w  ww. j  a v  a 2 s .  co m
        for (PropertyDescriptor desc : Introspector.getBeanInfo(object.getClass()).getPropertyDescriptors()) {
            Class<?> type = desc.getPropertyType();
            String fieldName = desc.getName();

            if ((!fieldName.startsWith("pc")) && (!ArrayUtils.contains(IGNORE_FIELDS, fieldName))
                    && (!Iterable.class.isAssignableFrom(type)) && (!type.isArray())) {

                try {
                    Object fieldValue;
                    if (desc.getReadMethod() == null) {
                        final Field field = object.getClass().getDeclaredField(fieldName);
                        field.setAccessible(true);
                        fieldValue = field.get(object);
                    } else {
                        fieldValue = desc.getReadMethod().invoke(object);
                    }

                    context.set(fieldName,
                            fieldValue == null ? StringUtils.EMPTY
                                    : (type.equals(Date.class) ? DataFormat.format((Date) fieldValue, false)
                                            : fieldValue));

                    LOG.debug("Add field {} with value {}", fieldName, fieldValue);
                } catch (Exception iae) {
                    LOG.error("Reading '{}' value error", fieldName, iae);
                }
            }
        }
    } catch (IntrospectionException ie) {
        LOG.error("Reading class attributes error", ie);
    }

    if (object instanceof Any) {
        Any<?, ?, ?> any = (Any<?, ?, ?>) object;
        if (any.getRealm() != null) {
            context.set("realm", any.getRealm().getName());
        }
    }

    return context;
}

From source file:org.apache.syncope.core.util.jexl.JexlUtil.java

public static JexlContext addFieldsToContext(final Object attributable, final JexlContext jexlContext) {
    JexlContext context = jexlContext == null ? new MapContext() : jexlContext;

    try {/*w  ww.  j  a v a  2s . co m*/
        for (PropertyDescriptor desc : Introspector.getBeanInfo(attributable.getClass())
                .getPropertyDescriptors()) {
            final Class<?> type = desc.getPropertyType();
            final String fieldName = desc.getName();

            if ((!fieldName.startsWith("pc")) && (!ArrayUtils.contains(IGNORE_FIELDS, fieldName))
                    && (!Iterable.class.isAssignableFrom(type)) && (!type.isArray())) {
                try {
                    final Method getter = desc.getReadMethod();

                    final Object fieldValue;

                    if (getter == null) {
                        final Field field = attributable.getClass().getDeclaredField(fieldName);
                        field.setAccessible(true);
                        fieldValue = field.get(attributable);
                    } else {
                        fieldValue = getter.invoke(attributable);
                    }

                    context.set(fieldName,
                            fieldValue == null ? ""
                                    : (type.equals(Date.class) ? DataFormat.format((Date) fieldValue, false)
                                            : fieldValue));

                    LOG.debug("Add field {} with value {}", fieldName, fieldValue);

                } catch (Exception iae) {
                    LOG.error("Reading '{}' value error", fieldName, iae);
                }
            }
        }
    } catch (IntrospectionException ie) {
        LOG.error("Reading class attributes error", ie);
    }

    return context;
}

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

/**
 * Adds an extended property to the BeanMapping. 
 * //from w  w  w .j  a  v  a2 s  . c  o m
 * @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: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;
    }// w  ww . j av a 2  s  .  c  o  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;
}

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

static PropertyDescriptor[] getInterfacePropertyDescriptors(Class<?> interfaceClass) {
    List<PropertyDescriptor> propDescriptors = new ArrayList<PropertyDescriptor>();
    // Add prop descriptors for interface passed in
    propDescriptors.addAll(Arrays.asList(PropertyUtils.getPropertyDescriptors(interfaceClass)));

    // Look for interface inheritance. If super interfaces are found, recurse up the hierarchy tree and add prop
    // descriptors for each interface found.
    // PropertyUtils.getPropertyDescriptors() does not correctly walk the inheritance hierarchy for interfaces.
    Class<?>[] interfaces = interfaceClass.getInterfaces();
    if (interfaces != null) {
        for (Class<?> superInterfaceClass : interfaces) {
            List<PropertyDescriptor> superInterfacePropertyDescriptors = Arrays
                    .asList(getInterfacePropertyDescriptors(superInterfaceClass));
            /*/* w  ww . j  a v  a  2s  . c  om*/
             * #1814758
             * Check for existing descriptor with the same name to prevent 2 property descriptors with the same name being added
             * to the result list.  This caused issues when getter and setter of an attribute on different interfaces in
             * an inheritance hierarchy
             */
            for (PropertyDescriptor superPropDescriptor : superInterfacePropertyDescriptors) {
                PropertyDescriptor existingPropDescriptor = findPropDescriptorByName(propDescriptors,
                        superPropDescriptor.getName());
                if (existingPropDescriptor == null) {
                    propDescriptors.add(superPropDescriptor);
                } else {
                    try {
                        if (existingPropDescriptor.getReadMethod() == null) {
                            existingPropDescriptor.setReadMethod(superPropDescriptor.getReadMethod());
                        }
                        if (existingPropDescriptor.getWriteMethod() == null) {
                            existingPropDescriptor.setWriteMethod(superPropDescriptor.getWriteMethod());
                        }
                    } catch (IntrospectionException e) {
                        throw new MappingException(e);
                    }

                }
            }
        }
    }
    return propDescriptors.toArray(new PropertyDescriptor[propDescriptors.size()]);
}

From source file:com.github.dozermapper.core.util.ReflectionUtils.java

public static Class<?> determineGenericsType(Class<?> parentClazz, PropertyDescriptor propDescriptor) {
    Class<?> result = null;
    //Try getter and setter to determine the Generics type in case one does not exist
    if (propDescriptor.getWriteMethod() != null) {
        result = determineGenericsType(parentClazz, propDescriptor.getWriteMethod(), false);
    }// www .ja va 2  s.co  m

    if (result == null && propDescriptor.getReadMethod() != null) {
        result = determineGenericsType(parentClazz, propDescriptor.getReadMethod(), true);
    }

    return result;
}

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

/**
 * Returns the initialized property.//from  ww w  .j  av a  2  s.  c o m
 * 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.paxml.util.ReflectUtils.java

/**
 * Get a specific type of property descriptors, except the "class" property.
 * /*from   www. ja va2  s .  c om*/
 * @param clazz
 *            the class
 * @param type
 *            the type filter, null means no filtering
 * @return the list of property descriptors.
 */
public static List<PropertyDescriptor> getPropertyDescriptors(Class clazz, PropertyDescriptorType type) {
    List<PropertyDescriptor> list = new ArrayList<PropertyDescriptor>();
    for (PropertyDescriptor pd : BeanUtils.getPropertyDescriptors(clazz)) {
        if ("class".equals(pd.getName())) {
            continue;
        }
        switch (type) {
        case GETTER:
            if (pd.getReadMethod() != null) {
                list.add(pd);
            }
            break;
        case SETTER:
            if (pd.getWriteMethod() != null) {
                list.add(pd);
            }
            break;
        default:
            list.add(pd);
        }

    }
    return list;
}