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.apache.jmeter.testbeans.gui.GenericTestBeanCustomizer.java

/**
 * Identify the property from the descriptor.
 * /*from   w ww .  j av a 2 s  .  co m*/
 * @param pd
 * @return the property details
 */
private static String getDetails(PropertyDescriptor pd) {
    StringBuilder sb = new StringBuilder();
    sb.append(pd.getReadMethod().getDeclaringClass().getName());
    sb.append('#');
    sb.append(pd.getName());
    sb.append('(');
    sb.append(pd.getPropertyType().getCanonicalName());
    sb.append(')');
    return sb.toString();
}

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

static PropertyDescriptor[] getInterfacePropertyDescriptors(Class<?> interfaceClass) {
    List<PropertyDescriptor> propDescriptors = new ArrayList<>();
    // 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));
            /*//from  w  w w  .  j  ava2  s  .  c o  m
             * #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.ksmpartners.ernie.util.TestUtil.java

/**
 * Test setter and getter call and make sure they match.
 * <p>/* ww  w .j  a  va 2  s. c om*/
 * @param property the property to be set
 * @param setValue the value to be set
 * @param qName qualified name for error reporting
 */
private static void testProperty(Object target, PropertyDescriptor property, Object setValue, String qName) {

    // flag indicating whether a comparison should be done at the end
    boolean expectMatch = true;

    // call setter (if exists)
    if (property.getWriteMethod() != null) {
        invokeMethod(target, property.getWriteMethod(), new Object[] { setValue }, qName);
    } else {
        Assert.assertFalse(true, "Property " + qName + " does not have the required setter.");
        expectMatch = false;
    }

    // call getter (if exists)
    Object getValue = null;
    if (property.getReadMethod() != null) {
        getValue = invokeMethod(target, property.getReadMethod(), null, qName);
    } else {
        Assert.assertFalse(true, "Property " + qName + " does not have the required getter.");
        expectMatch = false;
    }

    // if expecting a match, compare
    // if they are not the same instance, assert that they have equality
    if (expectMatch && setValue != getValue)
        Assert.assertEquals(getValue, setValue,
                "Values did not match for getter/setter call on field " + qName);
}

From source file:com.thesoftwarefactory.vertx.web.model.Form.java

/**
 * Build a new Form instance from the specified class
 * //w  w w  .  java  2  s  . c om
 * @param cls
 * @param fieldPrefix: if not null, the prefix is prepended to each field name 
 * @return
 */
public final static <T> Form<T> fromClass(Class<T> cls, String fieldPrefix) {
    Objects.requireNonNull(cls);

    Form<T> result = new Form<T>();
    if (fieldPrefix != null) {
        result.fieldPrefix = fieldPrefix;
    }

    // discover properties
    for (PropertyDescriptor property : BeanUtils.getPropertyDescriptors(cls)) {
        if (property.getReadMethod() != null && property.getWriteMethod() != null) {
            // the property has a getter and setter
            String fieldName = fieldPrefix != null ? fieldPrefix + property.getName() : property.getName();
            result.addField(result.new Field(fieldName, Form.fieldTypefromClass(property.getPropertyType())));
        }
    }

    return result;
}

From source file:de.escalon.hypermedia.spring.uber.UberUtils.java

/**
 * Recursively converts object to nodes of uber data.
 *
 * @param objectNode/* w w w .ja  v  a  2s  .c  o  m*/
 *         to append to
 * @param object
 *         to convert
 */
public static void toUberData(AbstractUberNode objectNode, Object object) {
    Set<String> filtered = FILTER_RESOURCE_SUPPORT;
    if (object == null) {
        return;
    }

    try {
        // TODO: move all returns to else branch of property descriptor handling
        if (object instanceof Resource) {
            Resource<?> resource = (Resource<?>) object;
            objectNode.addLinks(resource.getLinks());
            toUberData(objectNode, resource.getContent());
            return;
        } else if (object instanceof Resources) {
            Resources<?> resources = (Resources<?>) object;

            // TODO set name using EVO see HypermediaSupportBeanDefinitionRegistrar

            objectNode.addLinks(resources.getLinks());

            Collection<?> content = resources.getContent();
            toUberData(objectNode, content);
            return;
        } else if (object instanceof ResourceSupport) {
            ResourceSupport resource = (ResourceSupport) object;

            objectNode.addLinks(resource.getLinks());

            // wrap object attributes below to avoid endless loop

        } else if (object instanceof Collection) {
            Collection<?> collection = (Collection<?>) object;
            for (Object item : collection) {
                // TODO name must be repeated for each collection item
                UberNode itemNode = new UberNode();
                objectNode.addData(itemNode);
                toUberData(itemNode, item);
            }
            return;
        }
        if (object instanceof Map) {
            Map<?, ?> map = (Map<?, ?>) object;
            for (Entry<?, ?> entry : map.entrySet()) {
                String key = entry.getKey().toString();
                Object content = entry.getValue();
                Object value = getContentAsScalarValue(content);
                UberNode entryNode = new UberNode();
                objectNode.addData(entryNode);
                entryNode.setName(key);
                if (value != null) {
                    entryNode.setValue(value);
                } else {
                    toUberData(entryNode, content);
                }
            }
        } else {
            Map<String, PropertyDescriptor> propertyDescriptors = PropertyUtils.getPropertyDescriptors(object);
            for (PropertyDescriptor propertyDescriptor : propertyDescriptors.values()) {
                String name = propertyDescriptor.getName();
                if (filtered.contains(name)) {
                    continue;
                }
                UberNode propertyNode = new UberNode();
                Object content = propertyDescriptor.getReadMethod().invoke(object);

                if (isEmptyCollectionOrMap(content, propertyDescriptor.getPropertyType())) {
                    continue;
                }

                Object value = getContentAsScalarValue(content);
                propertyNode.setName(name);
                objectNode.addData(propertyNode);
                if (value != null) {
                    // for each scalar property of a simple bean, add valuepair nodes to data
                    propertyNode.setValue(value);
                } else {
                    toUberData(propertyNode, content);
                }
            }

            Field[] fields = object.getClass().getFields();
            for (Field field : fields) {
                String name = field.getName();
                if (!propertyDescriptors.containsKey(name)) {
                    Object content = field.get(object);
                    Class<?> type = field.getType();
                    if (isEmptyCollectionOrMap(content, type)) {
                        continue;
                    }
                    UberNode propertyNode = new UberNode();

                    Object value = getContentAsScalarValue(content);
                    propertyNode.setName(name);
                    objectNode.addData(propertyNode);
                    if (value != null) {
                        // for each scalar property of a simple bean, add valuepair nodes to data
                        propertyNode.setValue(value);
                    } else {
                        toUberData(propertyNode, content);
                    }

                }
            }
        }
    } catch (Exception ex) {
        throw new RuntimeException("failed to transform object " + object, ex);
    }
}

From source file:jp.co.ctc_g.jfw.core.util.Beans.java

private static Object readPseudoPropertyValueNamed0(String propertyName, Object bean) {
    Object value = null;//from w w  w.  java2 s  .  c o m
    try {
        PropertyDescriptor pd = findPropertyDescriptorFor(bean.getClass(), propertyName);
        // ???????
        if (pd != null) {
            Method reader = pd.getReadMethod();
            if (reader != null) {
                reader.setAccessible(true);
                value = reader.invoke(bean);
            } else {
                if (L.isDebugEnabled()) {
                    Map<String, Object> replace = new HashMap<String, Object>(1);
                    replace.put("property", propertyName);
                    L.debug(Strings.substitute(R.getString("E-UTIL#0012"), replace));
                }
            }
            // ???????
        } else {
            Field f = bean.getClass().getField(propertyName);
            if (f != null && !Modifier.isStatic(f.getModifiers())) {
                f.setAccessible(true);
                value = f.get(bean);
            } else {
                if (L.isDebugEnabled()) {
                    Map<String, Object> replace = new HashMap<String, Object>(1);
                    replace.put("property", propertyName);
                    L.debug(Strings.substitute(R.getString("D-UTIL#0019"), replace));
                }
            }
        }
    } catch (SecurityException e) {
        throw new InternalException(Beans.class, "E-UTIL#0010", e);
    } catch (NoSuchFieldException e) {
        Map<String, String> replace = new HashMap<String, String>(1);
        replace.put("property", propertyName);
        throw new InternalException(Beans.class, "E-UTIL#0011", replace, e);
    } catch (IllegalArgumentException e) {
        Map<String, String> replace = new HashMap<String, String>(1);
        replace.put("property", propertyName);
        throw new InternalException(Beans.class, "E-UTIL#0012", replace, e);
    } catch (IllegalAccessException e) {
        throw new InternalException(Beans.class, "E-UTIL#0013", e);
    } catch (InvocationTargetException e) {
        Map<String, String> replace = new HashMap<String, String>(2);
        replace.put("class", bean.getClass().getName());
        replace.put("property", propertyName);
        throw new InternalException(Beans.class, "E-UTIL#0014", replace, e);
    }
    return value;
}

From source file:org.bibsonomy.model.util.BibTexUtils.java

/**
 * return a bibtex string representation of the given bibtex object
 * // w  w  w .jav  a2  s .  c  o m
 * @param bib - a bibtex object
 * @param mode - the serializing mode (parse misc fields or include misc fields as they are)
 * @return String bibtexString
 * 
 * TODO use BibTex.DEFAULT_OPENBRACKET etc.
 * 
 */
public static String toBibtexString(final BibTex bib, SerializeBibtexMode mode) {
    try {
        final BeanInfo bi = Introspector.getBeanInfo(bib.getClass());

        /*
         * start with entrytype and key
         */
        final StringBuilder buffer = new StringBuilder(
                "@" + bib.getEntrytype() + "{" + bib.getBibtexKey() + ",\n");

        /*
         * append all other fields
         */
        for (final PropertyDescriptor d : bi.getPropertyDescriptors()) {
            final Method getter = d.getReadMethod();
            // loop over all String attributes
            final Object o = getter.invoke(bib, (Object[]) null);
            if (String.class.equals(d.getPropertyType()) && o != null
                    && !EXCLUDE_FIELDS.contains(d.getName())) {

                /*
                 * Strings containing whitespace give empty fields ... we ignore them 
                 */
                String value = ((String) o);
                if (present(value)) {
                    if (!NUMERIC_PATTERN.matcher(value).matches()) {
                        value = DEFAULT_OPENING_BRACKET + value + DEFAULT_CLOSING_BRACKET;
                    }
                    buffer.append("  " + d.getName().toLowerCase() + " = " + value + ",\n");
                }
            }
        }
        /*
         * process miscFields map, if present
         */
        if (present(bib.getMiscFields())) {
            if (mode.equals(SerializeBibtexMode.PARSED_MISCFIELDS) && !bib.isMiscFieldParsed()) {
                // parse misc field, if not yet done
                bib.parseMiscField();
            }
            buffer.append(serializeMiscFields(bib.getMiscFields(), true));
        }

        /*
         * include plain misc fields if desired
         */
        if (mode.equals(SerializeBibtexMode.PLAIN_MISCFIELDS) && present(bib.getMisc())) {
            buffer.append("  " + bib.getMisc() + ",\n");
        }
        /*
         * add month
         */
        final String month = bib.getMonth();
        if (present(month)) {
            // we don't add {}, this is done by getMonth(), if necessary
            buffer.append("  month = " + getMonth(month) + ",\n");
        }
        /*
         * add abstract
         */
        final String bibAbstract = bib.getAbstract();
        if (present(bibAbstract)) {
            buffer.append("  abstract = {" + bibAbstract + "},\n");
        }
        /*
         * remove last comma
         */
        buffer.delete(buffer.lastIndexOf(","), buffer.length());
        buffer.append("\n}");

        return buffer.toString();

    } catch (IntrospectionException ex) {
        ex.printStackTrace();
    } catch (InvocationTargetException ex) {
        ex.printStackTrace();
    } catch (IllegalAccessException ex) {
        ex.printStackTrace();
    }
    return null;
}

From source file:jp.terasoluna.fw.util.GenericPropertyUtil.java

/**
 * <code>JavaBean</code>??? ??
 * @param bean <code>JavaBean</code>
 * @param name <code>Generics</code>????
 * @return <code>JavaBean</code>?????
 * @throws IllegalArgumentException <code>JavaBean</code>?? ??????????
 *//*from   ww w. j ava 2  s.  c  o  m*/
protected static Method getMethod(Object bean, String name) throws IllegalArgumentException {
    PropertyDescriptor descriptor = null;
    try {
        descriptor = PropertyUtils.getPropertyDescriptor(bean, name);
    } catch (IllegalAccessException e) {
        throw new IllegalArgumentException(
                "Failed to detect getter for " + bean.getClass().getName() + "#" + name, e);
    } catch (InvocationTargetException e) {
        throw new IllegalArgumentException(
                "Failed to detect getter for " + bean.getClass().getName() + "#" + name, e);
    } catch (NoSuchMethodException e) {
        throw new IllegalArgumentException(
                "Failed to detect getter for " + bean.getClass().getName() + "#" + name, e);
    }
    Method method = null;
    if (descriptor != null) {
        method = descriptor.getReadMethod();
    }
    if (method == null) {
        throw new IllegalArgumentException(bean.getClass().getName() + " has no getter for property " + name);
    }
    return method;
}

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

/**
 * Checks whether the specified property is inherited from a super class
 *
 * @param clz The class to check/*from   w w w. j a v  a  2  s. c o m*/
 * @param propertyName The property name
 * @return True if the property is inherited
 */
public static boolean isPropertyInherited(Class clz, String propertyName) {
    if (clz == null)
        return false;
    if (StringUtils.isBlank(propertyName))
        throw new IllegalArgumentException("Argument [propertyName] cannot be null or blank");

    Class superClass = clz.getSuperclass();

    PropertyDescriptor pd = BeanUtils.getPropertyDescriptor(superClass, propertyName);
    if (pd != null && pd.getReadMethod() != null) {
        return true;
    }
    return false;
}

From source file:acmi.l2.clientmod.xdat.Controller.java

private static List<PropertySheetItem> loadProperties(Object obj) {
    Class<?> objClass = obj.getClass();
    List<PropertySheetItem> list = new ArrayList<>();
    while (objClass != Object.class) {
        try {//from   w ww  .j a v  a2 s  .co m
            List<String> names = Arrays.stream(objClass.getDeclaredFields())
                    .map(field -> field.getName().replace("Prop", "")).collect(Collectors.toList());
            BeanInfo beanInfo = Introspector.getBeanInfo(objClass, objClass.getSuperclass());
            PropertyDescriptor[] propertyDescriptors = beanInfo.getPropertyDescriptors();
            Arrays.sort(propertyDescriptors,
                    (pd1, pd2) -> Integer.compare(names.indexOf(pd1.getName()), names.indexOf(pd2.getName())));
            for (PropertyDescriptor descriptor : propertyDescriptors) {
                if ("metaClass".equals(descriptor.getName()))
                    continue;

                if (Collection.class.isAssignableFrom(descriptor.getPropertyType()))
                    continue;

                AnnotatedElement getter = descriptor.getReadMethod();
                if (getter.isAnnotationPresent(Deprecated.class) || getter.isAnnotationPresent(Hide.class))
                    continue;

                String description = "";
                if (getter.isAnnotationPresent(Description.class))
                    description = getter.getAnnotation(Description.class).value();
                Class<? extends PropertyEditor<?>> propertyEditorClass = null;
                if (descriptor.getPropertyType() == Boolean.class
                        || descriptor.getPropertyType() == Boolean.TYPE) {
                    propertyEditorClass = BooleanPropertyEditor.class;
                } else if (getter.isAnnotationPresent(Tex.class)) {
                    propertyEditorClass = TexturePropertyEditor.class;
                } else if (getter.isAnnotationPresent(Sysstr.class)) {
                    propertyEditorClass = SysstringPropertyEditor.class;
                }
                BeanProperty property = new BeanProperty(descriptor, objClass.getSimpleName(), description,
                        propertyEditorClass);
                list.add(property);
            }
        } catch (IntrospectionException e) {
            e.printStackTrace();
        }
        objClass = objClass.getSuperclass();
    }
    return list;
}