Example usage for org.springframework.beans BeanUtils getPropertyDescriptor

List of usage examples for org.springframework.beans BeanUtils getPropertyDescriptor

Introduction

In this page you can find the example usage for org.springframework.beans BeanUtils getPropertyDescriptor.

Prototype

@Nullable
public static PropertyDescriptor getPropertyDescriptor(Class<?> clazz, String propertyName)
        throws BeansException 

Source Link

Document

Retrieve the JavaBeans PropertyDescriptors for the given property.

Usage

From source file:org.jdal.vaadin.ui.form.ComboBoxFieldBuilder.java

/**
 * Fill the ComboBox with items from PersistentService
 * @param combo ComboBox to fill//www  .  j a  va 2  s  .  c o m
 * @param clazz Class of Bean containing property name
 * @param name property name
 */
protected void fillComboBox(ComboBox combo, Class<?> clazz, String name) {
    PropertyDescriptor pd = BeanUtils.getPropertyDescriptor(clazz, name);
    Dao<?, Serializable> service = persistentServiceFactory.createPersistentService(pd.getPropertyType());
    // fill combo
    Iterator<?> iter = service.getAll().iterator();
    while (iter.hasNext())
        combo.addItem(iter.next());
}

From source file:com.ewcms.common.query.mongo.PropertyConvert.java

/**
 * ?{@link RuntimeException}/*from w  ww. j a v a  2  s.  co  m*/
 * 
 * @param name  ???{@literal null}
 * @return {@value Class<?>}
 */
public Class<?> getPropertyType(String propertyName) {
    if (!StringUtils.hasText(propertyName)) {
        throw new IllegalArgumentException("Property's name must not null or empty!");
    }

    String[] names = StringUtils.tokenizeToStringArray(propertyName, NESTED);
    Class<?> type = beanClass;
    PropertyDescriptor pd = null;
    for (String name : names) {
        pd = BeanUtils.getPropertyDescriptor(type, name);
        if (pd == null) {
            logger.error("\"{}\" property isn't exist.", propertyName);
            throw new RuntimeException(propertyName + " property isn't exist.");
        }
        type = pd.getPropertyType();
    }

    if (type.isArray()) {
        return type.getComponentType();
    }

    if (Collection.class.isAssignableFrom(type)) {
        Method method = pd.getReadMethod();
        if (method == null) {
            logger.error("\"{}\" property is not read method.", propertyName);
            throw new RuntimeException(propertyName + " property is not read method.");
        }
        ParameterizedType returnType = (ParameterizedType) method.getGenericReturnType();
        if (returnType.getActualTypeArguments().length > 0) {
            return (Class<?>) returnType.getActualTypeArguments()[0];
        }
        logger.error("\"{}\" property is collection,but it's not generic.", propertyName);
        throw new RuntimeException(propertyName + " property is collection,but it's not generic.");
    }

    return type;
}

From source file:com.expedia.seiso.domain.meta.DynaItem.java

public DynaItem(@NonNull Item item) {
    this.item = item;
    this.itemClass = item.getClass();

    String metaKeyFieldName = null;

    // Use currClass to search up the inheritance hierarchy. We need this for example to find the @Key for Vip
    // subclasses, since the @Key is defined in Vip.
    Class<?> currClass = itemClass;
    do {/*from   ww  w  .j  a va2s. c om*/
        val fields = currClass.getDeclaredFields();
        for (val field : fields) {
            val anns = field.getAnnotations();
            for (val ann : anns) {
                if (ann.annotationType() == Key.class) {
                    metaKeyFieldName = field.getName();
                }
            }
        }
    } while (metaKeyFieldName == null && (currClass = currClass.getSuperclass()) != null);

    // FIXME This doesn't handle compound keys. Use the ItemKey instead! [WLW]
    // If there's no explicit @Key, then use the ID by default.
    if (metaKeyFieldName == null) {
        metaKeyFieldName = "id";
    }

    this.metaKeyProperty = BeanUtils.getPropertyDescriptor(itemClass, metaKeyFieldName);
    val metaKeyGetter = metaKeyProperty.getReadMethod();

    try {
        this.metaKey = (Serializable) metaKeyGetter.invoke(item);
    } catch (IllegalAccessException | InvocationTargetException e) {
        throw new RuntimeException(e);
    }

    // log.trace("Using key {}={} for itemClass={}", metaKeyFieldName, metaKey, itemClass.getSimpleName());
}

From source file:arena.utils.ReflectionUtils.java

public static String[] getAttributeNamesUsingGetter(Class<?> entityClass) {
    //        return BeanUtils.getPropertyDescriptors(entityClass);
    Class<?> clsMe = entityClass;
    List<String> voFieldNames = new ArrayList<String>();

    while (clsMe != null) {
        Field[] fields = clsMe.getDeclaredFields();

        for (int n = 0; n < fields.length; n++) {
            int modifiers = fields[n].getModifiers();
            if (!Modifier.isPublic(modifiers) && !Modifier.isStatic(modifiers)) {
                String fieldName = fields[n].getName();
                try {
                    PropertyDescriptor pd = BeanUtils.getPropertyDescriptor(entityClass, fieldName);
                    if (pd.getReadMethod() != null) {
                        voFieldNames.add(fieldName);
                    }//from  w  ww.  j a  va2 s  .com
                } catch (Throwable err) {
                    // skip
                }
            }
        }

        // Loop back to parent class
        clsMe = clsMe.getSuperclass();
    }
    return voFieldNames.toArray(new String[voFieldNames.size()]);
}

From source file:com.doculibre.constellio.utils.connector.ConnectorPropertyInheritanceResolver.java

private static String getStringPropertyValue(Object bean, String propertyName) {
    try {//from ww  w  .  j  a  va2 s  .c o m
        PropertyDescriptor propertyDescriptor = BeanUtils.getPropertyDescriptor(bean.getClass(), propertyName);
        return (String) propertyDescriptor.getReadMethod().invoke(bean);
    } catch (IllegalArgumentException e) {
        throw new RuntimeException(e);
    } catch (IllegalAccessException e) {
        throw new RuntimeException(e);
    } catch (InvocationTargetException e) {
        throw new RuntimeException(e);
    }
}

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

/**
 * Adds an extended property to the BeanMapping. 
 * //ww  w .j  a v  a 2 s .com
 * @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.bstek.dorado.view.widget.layout.LayoutTextParserDispatcher.java

@Override
@SuppressWarnings("unchecked")
public Object parse(char[] charArray, TextParseContext context) throws Exception {
    LayoutDefinition layout = null;//from w  w w  . ja  v  a  2  s .  co  m
    String layoutType = parseHeader(charArray, context);
    if (StringUtils.isEmpty(layoutType)) {
        layoutType = layoutTypeRegistry.getDefaultType();
    }
    LayoutTypeRegisterInfo info = layoutTypeRegistry.getRegisterInfo(layoutType);
    if (info != null) {
        layout = new LayoutDefinition();
        layout.setType(info.getType());
        Class<? extends Layout> classType = info.getClassType();
        layout.setImplType(classType);
        TextParser layoutParser = textParserHelper.getTextParser(info.getClassType());

        Map<String, Object> attributes = (Map<String, Object>) layoutParser.parse(charArray, context);

        Map<String, Object> style = null;

        for (Map.Entry<String, Object> entry : attributes.entrySet()) {
            String key = entry.getKey();
            if (BeanUtils.getPropertyDescriptor(classType, key) != null) {
                layout.setProperty(key, entry.getValue());
            } else {
                if (style == null) {
                    style = new HashMap<String, Object>();
                }
                style.put(key, entry.getValue());
            }
        }

        if (style != null) {
            layout.setProperty("style", style);
        }
    } else {
        throw new TextParseException("Unrecognized layout definition [" + layoutType + "].");
    }
    return layout;
}

From source file:arena.utils.ReflectionUtils.java

public static Class<?> getAttributeTypeUsingGetter(String attributeName, Class<?> entityClass) {
    return BeanUtils.getPropertyDescriptor(entityClass, attributeName).getPropertyType();
}

From source file:com.expedia.seiso.domain.meta.DynaItem.java

/**
 * Returns the specified property value for the underlying item.
 * /* w ww  . j  av  a 2  s  .c  o m*/
 * @param propertyName
 *            Property name
 * @return Property value
 */
@SneakyThrows
public Object getPropertyValue(@NonNull String propertyName) {
    val desc = BeanUtils.getPropertyDescriptor(itemClass, propertyName);
    val getter = desc.getReadMethod();
    return getter.invoke(item);
}

From source file:org.springjutsu.validation.util.PathUtils.java

/**
 * Determine the class of each step in the selected path on the target class. 
 * @param clazz Class to check /*from   ww  w.  ja va  2 s .c om*/
 * @param path Path to check
 * @param unwrapCollectionTypes if true returns the parameterized collection type
 * @return array of classes for each step of path.
 */
public static Class<?>[] getClassesForPathTokens(Class<?> clazz, String path, boolean unwrapCollectionTypes) {
    if (path == null || path.trim().isEmpty()) {
        return null;
    }
    Class<?> intermediateClass = clazz;
    String[] pathTokens = path.split("\\.");
    Class<?>[] pathClasses = new Class<?>[pathTokens.length];

    for (int i = 0; i < pathTokens.length; i++) {
        String token = pathTokens[i];
        token = token.replaceAll("\\[[^\\]]+\\]$", "");
        PropertyDescriptor descriptor = BeanUtils.getPropertyDescriptor(intermediateClass, token);
        if (descriptor == null) {
            return null;
        } else if (List.class.isAssignableFrom(descriptor.getPropertyType())) {
            intermediateClass = TypeDescriptor.nested(ReflectionUtils.findField(intermediateClass, token), 1)
                    .getObjectType();
        } else if (descriptor.getPropertyType().isArray()) {
            intermediateClass = descriptor.getPropertyType().getComponentType();
        } else {
            intermediateClass = descriptor.getPropertyType();
        }
        if (unwrapCollectionTypes) {
            pathClasses[i] = intermediateClass;
        } else {
            pathClasses[i] = descriptor.getPropertyType();
        }
    }
    return pathClasses;
}