Example usage for java.beans PropertyDescriptor getName

List of usage examples for java.beans PropertyDescriptor getName

Introduction

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

Prototype

public String getName() 

Source Link

Document

Gets the programmatic name of this feature.

Usage

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

/**
 * Get a Map of non-null bean properties for an object.
 * /*from ww  w . ja  v a 2 s.  com*/
 * @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:edu.harvard.med.screensaver.model.AbstractEntityInstanceTest.java

/**
 * Subclasses should call this method to build their TestSuite, as it will
 * include tests for the test methods declared in this class, as well as tests
 * for each entity property found in the specified AbstractEntity class.
 * /* w ww. j a va 2 s.  c  o  m*/
 * @param entityTestClass
 * @param entityClass
 * @return
 */
public static TestSuite buildTestSuite(Class<? extends AbstractEntityInstanceTest> entityTestClass,
        Class<? extends AbstractEntity> entityClass) {
    TestSuite testSuite = new TestSuite(entityTestClass);
    BeanInfo beanInfo;
    try {
        beanInfo = Introspector.getBeanInfo(entityClass);
        // add all the property-specific tests for this entity class
        for (PropertyDescriptor propertyDescriptor : beanInfo.getPropertyDescriptors()) {
            if (propertyDescriptor.getName().equals("class")) {
                log.debug("not creating test for \"class\" property " + propertyDescriptor.getDisplayName());
            } else if (ModelIntrospectionUtil.isTransientProperty(propertyDescriptor)) {
                log.debug("not creating test for transient (non-persistent) property "
                        + propertyDescriptor.getDisplayName());
            } else /*if (ModelIntrospectionUtil.isToManyEntityRelationship(propertyDescriptor))*/ {
                propertyDescriptor = new GenericTypeAwarePropertyDescriptor(entityClass, propertyDescriptor);
                testSuite.addTest(new EntityPropertyTest(entityClass, propertyDescriptor));
            }
        }
    } catch (IntrospectionException e) {
        e.printStackTrace();
        fail(e.getMessage());
    }
    return testSuite;
}

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

/**
 * Copy non-null bean properties from one object to another.
 * // w ww  . ja  v  a2 s.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:cn.fql.utility.ClassUtility.java

/**
 * Import value to object according specified  <code>org.xml.sax.Attributes</code>
 *
 * @param obj  specified object instance
 * @param atts <code>org.xml.sax.Attributes</code>
 *///  w ww  .j av  a2s. c  o m
public static void importValueFromAttribute(Object obj, org.xml.sax.Attributes atts) {
    if (atts != null) {
        PropertyDescriptor[] pds;
        try {
            pds = exportPropertyDesc(obj.getClass());
            if (pds != null && pds.length > 0) {
                for (int i = 0; i < pds.length; i++) {
                    PropertyDescriptor pd = pds[i];
                    String strValue = atts.getValue(pd.getName());
                    if (strValue != null) {
                        Method setter = pd.getWriteMethod();
                        if (setter != null) {
                            Object value = ConvertUtils.convert(strValue, pd.getPropertyType());
                            Object[] params = { value };
                            setter.invoke(obj, params);
                        }
                    }
                }
            }
        } catch (Exception e) {
            System.out.println(e.getMessage());
        }
    }
}

From source file:com.palantir.ptoss.util.Reflections.java

/**
 * Returns a {@link Function} that will read values from the named field from a passed object.
 * @param klass type to read values from
 * @param returnType return type of read field
 * @param getter name of the field/*from   w w w.ja  v a  2s. co  m*/
 * @return a {@link Function} object that, when applied to an instance of <code>klass</code>, returns the
 * of type <code>returnType</code> that resides in field <code>getter</code>
 */
public static <F, T> Function<F, T> getterFunction(final Class<F> klass, final Class<T> returnType,
        String getter) {
    try {
        BeanInfo beanInfo = Introspector.getBeanInfo(klass);
        PropertyDescriptor[] props = beanInfo.getPropertyDescriptors();
        Method method = null;
        for (PropertyDescriptor descriptor : props) {
            if (descriptor.getName().equals(getter)) {
                method = descriptor.getReadMethod();
                break;
            }
        }
        if (method == null) {
            throw new IllegalStateException();
        }
        final Method readMethod = method;
        return new Function<F, T>() {
            public T apply(F from) {
                try {
                    return returnType.cast(readMethod.invoke(from));
                } catch (Exception e) {
                    Throwables.throwUncheckedException(e);
                    return null;
                }
            }
        };
    } catch (IntrospectionException e) {
        Throwables.throwUncheckedException(e);
        return null;
    }
}

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

/**
 * Adds an extended property to the BeanMapping. 
 * /*from   w  w  w . jav 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:com.mawujun.utils.bean.BeanUtils.java

/**
 * ????//from   w  w w.j  av  a 2 s . co m
 * null
 * @param source
 * @param target
 * @throws BeansException
 * @throws IntrospectionException
 */
public static void copyExcludeNull(Object source, Object target) throws IntrospectionException {

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

    Class<?> actualEditable = target.getClass();

    PropertyDescriptor[] targetPds = getPropertyDescriptors(actualEditable);

    for (PropertyDescriptor targetPd : targetPds) {
        if (targetPd.getWriteMethod() != null) {
            PropertyDescriptor sourcePd = getPropertyDescriptor(source.getClass(), targetPd.getName());
            if (sourcePd != null && sourcePd.getReadMethod() != null) {
                try {
                    Method readMethod = sourcePd.getReadMethod();
                    if (!Modifier.isPublic(readMethod.getDeclaringClass().getModifiers())) {
                        readMethod.setAccessible(true);
                    }
                    Object value = readMethod.invoke(source);
                    if (value == null) {//??
                        continue;
                    }
                    Method writeMethod = targetPd.getWriteMethod();
                    if (!Modifier.isPublic(writeMethod.getDeclaringClass().getModifiers())) {
                        writeMethod.setAccessible(true);
                    }
                    writeMethod.invoke(target, value);
                } catch (Throwable ex) {
                    throw new RuntimeException("Could not copy properties from source to target", ex);
                }
            }
        }
    }
}

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

/**
 * Returns the initialized property.//from w  ww.  j a  v 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:net.solarnetwork.util.ClassUtils.java

/**
 * Get a Map of non-null bean properties for an object.
 * /*from   w w  w. j  a v a 2 s  .co  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.mojodna.searchable.util.SearchableUtils.java

/**
 * Generate a list of field names for a given property.
 * /*from   ww  w  . j  ava2s  . com*/
 * @param descriptor Property descriptor.
 * @return Collection of field names.
 */
public static final Collection<String> getFieldnames(final PropertyDescriptor descriptor) {
    final Collection<String> fieldnames = new LinkedList<String>();

    String fieldname = descriptor.getName();

    for (final Class<? extends Annotation> annotationClass : Searchable.INDEXING_ANNOTATIONS) {
        final Annotation annotation = AnnotationUtils.getAnnotation(descriptor.getReadMethod(),
                annotationClass);
        if (annotation instanceof Searchable.Indexed) {
            final Searchable.Indexed i = (Searchable.Indexed) annotation;
            if (StringUtils.isNotBlank(i.name()))
                fieldname = i.name();

            // add any aliases
            fieldnames.addAll(Arrays.asList(i.aliases()));
        } else if (annotation instanceof Searchable.Stored) {
            final Searchable.Stored s = (Searchable.Stored) annotation;
            if (StringUtils.isNotBlank(s.name()))
                fieldname = s.name();

            // add any aliases
            fieldnames.addAll(Arrays.asList(s.aliases()));
        } else if (annotation instanceof Searchable.Sortable) {
            final Searchable.Sortable s = (Sortable) annotation;
            if (StringUtils.isNotBlank(s.name()))
                fieldname = s.name();
        }
    }

    // add the default field name
    fieldnames.add(fieldname);

    return fieldnames;
}