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.zht.framework.util.ZBeanUtil.java

@SuppressWarnings({ "unchecked", "rawtypes" })
public static Map convertBeanToMap(Object bean) {
    Map returnMap = null;// w  w w  .j  a  v  a 2 s .  c  om
    try {
        Class<?> type = bean.getClass();
        BeanInfo beanInfo = Introspector.getBeanInfo(type);
        PropertyDescriptor[] propertyDescriptors = beanInfo.getPropertyDescriptors();
        //           MethodAccess access = MethodAccess.get(type.getClass());
        returnMap = new HashMap();
        for (PropertyDescriptor property : propertyDescriptors) {
            String properName = property.getName();
            Method getter = property.getReadMethod();
            Object value = getter.invoke(bean);
            returnMap.put(properName, value);
            //
            //            Object value=access.invoke(bean,"get" + ZStrUtil.toUpCaseFirst(properName));
            //            if (value != null){
            //               returnMap.put(properName, value);
            //            }else{
            //               returnMap.put(properName, null);
            //            }

        }
    } catch (Exception e) {
        e.printStackTrace();
        return returnMap;
    }
    return returnMap;
}

From source file:io.fabric8.core.jmx.BeanUtils.java

public static List<String> getFields(Class clazz) {
    List<String> answer = new ArrayList<String>();

    try {//from   w w w.  ja  v  a  2  s  . co  m
        for (PropertyDescriptor desc : PropertyUtils.getPropertyDescriptors(clazz)) {
            if (desc.getReadMethod() != null) {
                answer.add(desc.getName());
            }
        }
    } catch (Exception e) {
        throw new FabricException("Failed to get property descriptors for " + clazz.toString(), e);
    }

    // few tweaks to maintain compatibility with existing views for now...
    if (clazz.getSimpleName().equals("Container")) {
        answer.add("parentId");
        answer.add("versionId");
        answer.add("profileIds");
        answer.add("childrenIds");
        answer.remove("fabricService");
    } else if (clazz.getSimpleName().equals("Profile")) {
        answer.add("id");
        answer.add("parentIds");
        answer.add("childIds");
        answer.add("containerCount");
        answer.add("containers");
        answer.add("fileConfigurations");
    } else if (clazz.getSimpleName().equals("Version")) {
        answer.add("id");
        answer.add("defaultVersion");
    }

    return answer;
}

From source file:net.sourceforge.pmd.util.fxdesigner.util.beans.SettingsPersistenceUtil.java

/**
 * Builds a settings model recursively for the given settings owner.
 * The properties which have a getter tagged with {@link PersistentProperty}
 * are retrieved for later serialisation.
 *
 * @param root The root of the settings owner hierarchy.
 *
 * @return The built model//from  w  w w.java 2 s.  c  om
 */
// test only
static SimpleBeanModelNode buildSettingsModel(SettingsOwner root) {
    SimpleBeanModelNode node = new SimpleBeanModelNode(root.getClass());

    for (PropertyDescriptor d : PropertyUtils.getPropertyDescriptors(root)) {
        if (d.getReadMethod() == null) {
            continue;
        }

        try {
            if (d.getReadMethod().isAnnotationPresent(PersistentSequence.class)) {

                Object val = d.getReadMethod().invoke(root);
                if (!Collection.class.isAssignableFrom(val.getClass())) {
                    continue;
                }

                @SuppressWarnings("unchecked")
                Collection<SettingsOwner> values = (Collection<SettingsOwner>) val;

                BeanModelNodeSeq<SimpleBeanModelNode> seq = new BeanModelNodeSeq<>(d.getName());

                for (SettingsOwner item : values) {
                    seq.addChild(buildSettingsModel(item));
                }

                node.addChild(seq);
            } else if (d.getReadMethod().isAnnotationPresent(PersistentProperty.class)) {
                node.addProperty(d.getName(), d.getReadMethod().invoke(root), d.getPropertyType());
            }
        } catch (IllegalAccessException | InvocationTargetException e) {
            e.printStackTrace();
        }

    }

    for (SettingsOwner child : root.getChildrenSettingsNodes()) {
        node.addChild(buildSettingsModel(child));
    }

    return node;
}

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

/**
 * Does this property contain any index-specific annotations?
 * /*from  w w w .  jav  a 2s.c  o  m*/
 * @param descriptor Property descriptor.
 * @return Whether this property contains any index-specific annotations. 
 */
public static final boolean containsIndexAnnotations(final PropertyDescriptor descriptor) {
    final Method readMethod = descriptor.getReadMethod();

    boolean containsIndexAnnotations = false;

    for (final Class<? extends Annotation> annotationClass : Searchable.INDEXING_ANNOTATIONS) {
        if (AnnotationUtils.isAnnotationPresent(readMethod, annotationClass))
            containsIndexAnnotations = true;
    }

    return containsIndexAnnotations;
}

From source file:com.fantasia.snakerflow.engine.SnakerHelper.java

private static String getProperty(NodeModel node) {
    StringBuffer buffer = new StringBuffer();
    buffer.append("props:{");
    try {/*from ww w.j av a  2  s.  c  o m*/
        PropertyDescriptor[] beanProperties = PropertyUtils.getPropertyDescriptors(node);
        for (PropertyDescriptor propertyDescriptor : beanProperties) {
            if (propertyDescriptor.getReadMethod() == null || propertyDescriptor.getWriteMethod() == null)
                continue;
            String name = propertyDescriptor.getName();
            String value = "";
            if (propertyDescriptor.getPropertyType() == String.class) {
                value = (String) BeanUtils.getProperty(node, name);
            } else {
                continue;
            }
            if (value == null || value.equals(""))
                continue;
            buffer.append(name);
            buffer.append(":{value:'");
            buffer.append(convert(value));
            buffer.append("'},");
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
    buffer.deleteCharAt(buffer.length() - 1);
    buffer.append("}}");
    return buffer.toString();
}

From source file:com.github.pfmiles.minvelocity.TemplateUtil.java

private static void putAllPojoVals(Object ctxPojo, Context ctx) {
    ctx.put("ParseUtil", ParseUtil.class);
    if (ctxPojo == null)
        return;//from  w w w.  jav a 2s  .com
    if (ctxPojo instanceof Map) {
        for (Map.Entry<?, ?> e : ((Map<?, ?>) ctxPojo).entrySet()) {
            ctx.put(e.getKey().toString(), e.getValue());
        }
    } else {
        BeanInfo bi;
        try {
            bi = Introspector.getBeanInfo(ctxPojo.getClass());
            for (PropertyDescriptor pd : bi.getPropertyDescriptors()) {
                if ("class".equals(pd.getName()))
                    continue;
                Method rm = pd.getReadMethod();
                if (rm != null)
                    ctx.put(pd.getName(), rm.invoke(ctxPojo));
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
}

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

/**
 * Does this property contain any sortable-specific annotations?
 * /*from ww w.j  av a  2 s .  co m*/
 * @param descriptor Property descriptor.
 * @return Whether this property contains any sortable-specific annotations.
 */
public static final boolean containsSortableAnnotations(final PropertyDescriptor descriptor) {
    return AnnotationUtils.isAnnotationPresent(descriptor.getReadMethod(), Searchable.Sortable.class);
}

From source file:org.apache.bval.util.PropertyAccess.java

private static Method getPropertyReadMethod(String propertyName, Class<?> beanClass) {
    for (PropertyDescriptor each : PropertyUtils.getPropertyDescriptors(beanClass)) {
        if (each.getName().equals(propertyName)) {
            return each.getReadMethod();
        }/*from   www .  ja v  a2  s .c  om*/
    }
    return null;
}

From source file:BeanUtil.java

/**
 * <p>Gets the specified attribute from the specified object.  For example,
 * <code>getObjectAttribute(o, "address.line1")</code> will return
 * the result of calling <code>o.getAddress().getLine1()</code>.<p>
 *
 * <p>The attribute specified may contain as many levels as you like. If at
 * any time a null reference is acquired by calling one of the successive
 * getter methods, then the return value from this method is also null.</p>
 *
 * <p>When reading from a boolean property the underlying bean introspector
 * first looks for an is&lt;Property&gt; read method, not finding one it will
 * still look for a get&lt;Property&gt; read method.  Not finding either, the
 * property is considered write-only.</p>
 *
 * @param bean the bean to set the property on
 * @param propertyNames the name of the propertie(s) to retrieve.  If this is
 *        null or the empty string, then <code>bean</code> will be returned.
 * @return the object value of the bean attribute
 *
 * @throws PropertyNotFoundException indicates the the given property
 *         could not be found on the bean
 * @throws NoSuchMethodException Not thrown
 * @throws InvocationTargetException if a specified getter method throws an
 *   exception./*  ww w. j  av a2  s.  c o m*/
 * @throws IllegalAccessException if a getter method is
 *   not public or property is write-only.
 */
public static Object getObjectAttribute(Object bean, String propertyNames)
        throws NoSuchMethodException, InvocationTargetException, IllegalAccessException {

    Object result = bean;

    StringTokenizer propertyTokenizer = new StringTokenizer(propertyNames, PROPERTY_SEPARATOR);

    // Run through the tokens, calling get methods and
    // replacing result with the new object each time.
    // If the result equals null, then simply return null.
    while (propertyTokenizer.hasMoreElements() && result != null) {
        Class resultClass = result.getClass();
        String currentPropertyName = propertyTokenizer.nextToken();

        PropertyDescriptor propertyDescriptor = getPropertyDescriptor(currentPropertyName, resultClass);

        Method readMethod = propertyDescriptor.getReadMethod();
        if (readMethod == null) {
            throw new IllegalAccessException(
                    "User is attempting to " + "read from a property that has no read method.  "
                            + " This is likely a write-only bean property.  Caused " + "by property ["
                            + currentPropertyName + "] on class [" + resultClass + "]");
        }

        result = readMethod.invoke(result, NO_ARGUMENTS_ARRAY);
    }

    return result;
}

From source file:org.shept.util.BeanUtilsExtended.java

/**
 * Merge the property values of the given source bean into the given target bean.
 * <p>Note: Only not-null values are merged into the given target bean.
 * 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/*from ww  w  .j a v a2 s.  co m*/
 * @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 mergeProperties(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 = getPropertyDescriptors(actualEditable);
    List<String> ignoreList = (ignoreProperties != null) ? Arrays.asList(ignoreProperties) : null;

    for (PropertyDescriptor targetPd : targetPds) {
        if (targetPd.getWriteMethod() != null
                && (ignoreProperties == null || (!ignoreList.contains(targetPd.getName())))) {
            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) {
                        Method writeMethod = targetPd.getWriteMethod();
                        if (!Modifier.isPublic(writeMethod.getDeclaringClass().getModifiers())) {
                            writeMethod.setAccessible(true);
                        }
                        writeMethod.invoke(target, value);
                    }
                } catch (Throwable ex) {
                    throw new FatalBeanException("Could not copy properties from source to target", ex);
                }
            }
        }
    }
}