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.eclipse.wb.tests.designer.core.util.reflect.ReflectionUtilsTest.java

/**
 * Test for {@link ReflectionUtils#getPropertyDescriptors(BeanInfo, Class)}.<br>
 * Protected getter and public setter./*ww w  . j  a  v  a2 s . com*/
 */
public void test_getPropertyDescriptors_protectedGetterPublicSetter() throws Exception {
    @SuppressWarnings("unused")
    class MyButton extends JPanel {
        private static final long serialVersionUID = 0L;

        protected String getTitle() {
            return null;
        }

        public void setTitle(String s) {
        }
    }
    // check properties
    {
        Set<String> names = getPropertyDescriptorNames(MyButton.class).keySet();
        assertThat(names).contains("title");
        assertThat(names).excludes("title(java.lang.String)");
    }
    // both getter and setter should be accessible
    {
        PropertyDescriptor descriptor = getPropertyDescriptorNames(MyButton.class).get("title");
        assertNotNull(descriptor);
        assertNotNull(descriptor.getReadMethod());
        assertNotNull(descriptor.getWriteMethod());
    }
}

From source file:BeanVector.java

/**
 * This method returns the index of an object representing the
 * mode value of a property name.//from  w ww .j a v a2s.  co  m
 * @param propertyName String value of the property name to calculate.
 * @throws java.lang.IllegalAccessException reflection exception
 * @throws java.beans.IntrospectionException reflection exception
 * @throws java.lang.reflect.InvocationTargetException reflection exception
 * @return int value of the mode index
 */
public int getModeIndex(String propertyName) throws java.lang.IllegalAccessException,
        java.beans.IntrospectionException, java.lang.reflect.InvocationTargetException {
    int index = -1;
    int max = 0;
    int count = 0;
    Object o = null;
    Object hold = null;
    Hashtable cache = new Hashtable();
    String currentClass = "";
    PropertyDescriptor pd = null;
    BeanVector bv = new BeanVector(this.size(), 0, this);
    bv.sortOnProperty(propertyName);

    for (int i = 0; i < bv.size(); i++) {
        if (!currentClass.equals(bv.elementAt(i).getClass().getName())) {
            pd = (PropertyDescriptor) cache.get(bv.elementAt(i).getClass().getName());

            if (pd == null) {
                PropertyDescriptor[] pds = Introspector.getBeanInfo(bv.elementAt(i).getClass())
                        .getPropertyDescriptors();
                boolean foundProperty = false;

                for (int pdi = 0; (pdi < pds.length) && !foundProperty; pdi++) {
                    if (pds[pdi].getName().equals(propertyName)) {
                        pd = pds[pdi];
                        cache.put(bv.elementAt(i).getClass().getName(), pd);
                        foundProperty = true;
                    }
                }
            }
        }

        if (hold == null) {
            hold = pd.getReadMethod().invoke(bv.elementAt(i));
        } else {
            o = pd.getReadMethod().invoke(bv.elementAt(i));

            if ((o != null) && o.equals(hold)) {
                count++;

                if (count > max) {
                    max = count;
                    index = this.indexOf(bv.elementAt(i));
                }
            } else {
                count = 1;
            }

            hold = o;
        }
    }

    return index;
}

From source file:org.apache.openjpa.lib.conf.ConfigurationImpl.java

/**
 * Create a property descriptor for the given value.
 *///from   ww w. ja  v a 2  s .co m
private PropertyDescriptor getPropertyDescriptor(Value val) throws IntrospectionException {
    String prop = val.getProperty();
    prop = prop.substring(prop.lastIndexOf('.') + 1);

    // set up property descriptor
    PropertyDescriptor pd;
    try {
        pd = new PropertyDescriptor(Introspector.decapitalize(prop), getClass());
    } catch (IntrospectionException ie) {
        // if there aren't any methods for this value(i.e., if it's a
        // dynamically-added value), then an IntrospectionException will
        // be thrown. Try to create a PD with no read or write methods.
        pd = new PropertyDescriptor(Introspector.decapitalize(prop), (Method) null, (Method) null);
    }
    pd.setDisplayName(findLocalized(prop + "-name", true, val.getScope()));
    pd.setShortDescription(findLocalized(prop + "-desc", true, val.getScope()));
    pd.setExpert("true".equals(findLocalized(prop + "-expert", false, val.getScope())));

    try {
        pd.setReadMethod(getClass().getMethod("get" + StringUtils.capitalize(prop), (Class[]) null));
        pd.setWriteMethod(getClass().getMethod("set" + StringUtils.capitalize(prop),
                new Class[] { pd.getReadMethod().getReturnType() }));
    } catch (Throwable t) {
        // if an error occurs, it might be because the value is a
        // dynamic property.
    }

    String type = findLocalized(prop + "-type", true, val.getScope());
    if (type != null)
        pd.setValue(ATTRIBUTE_TYPE, type);

    String cat = findLocalized(prop + "-cat", false, val.getScope());
    if (cat != null)
        pd.setValue(ATTRIBUTE_CATEGORY, cat);

    pd.setValue(ATTRIBUTE_XML, toXMLName(prop));

    String order = findLocalized(prop + "-displayorder", false, val.getScope());
    if (order != null)
        pd.setValue(ATTRIBUTE_ORDER, order);

    // collect allowed values from alias keys, listed values, and
    // interface implementors
    Collection<String> allowed = new TreeSet<String>();
    List<String> aliases = Collections.emptyList();
    if (val.getAliases() != null) {
        aliases = Arrays.asList(val.getAliases());
        for (int i = 0; i < aliases.size(); i += 2)
            allowed.add(aliases.get(i));
    }
    String[] vals = Strings.split(findLocalized(prop + "-values", false, val.getScope()), ",", 0);
    for (int i = 0; i < vals.length; i++)
        if (!aliases.contains(vals[i]))
            allowed.add(vals[i]);
    try {
        Class<?> intf = Class.forName(findLocalized(prop + "-interface", true, val.getScope()), false,
                getClass().getClassLoader());
        pd.setValue(ATTRIBUTE_INTERFACE, intf.getName());
        String[] impls = Services.getImplementors(intf);
        for (int i = 0; i < impls.length; i++)
            if (!aliases.contains(impls[i]))
                allowed.add(impls[i]);
    } catch (Throwable t) {
    }
    if (!allowed.isEmpty())
        pd.setValue(ATTRIBUTE_ALLOWED_VALUES, (String[]) allowed.toArray(new String[allowed.size()]));

    return pd;
}

From source file:org.evergreen.web.utils.beanutils.PropertyUtilsBean.java

/**
 * <p>Return an accessible property getter method for this property,
 * if there is one; otherwise return <code>null</code>.</p>
 *
 * <p><strong>FIXME</strong> - Does not work with DynaBeans.</p>
 *
 * @param clazz The class of the read method will be invoked on
 * @param descriptor Property descriptor to return a getter for
 * @return The read method// www .j  a va2  s . c  o  m
 */
protected Method getReadMethod(Class clazz, PropertyDescriptor descriptor) {
    return (MethodUtils.getAccessibleMethod(clazz, descriptor.getReadMethod()));
}

From source file:com.twinsoft.convertigo.beans.core.DatabaseObject.java

public Element toXml(Document document) throws EngineException {
    Element element = document.createElement(getDatabaseType().toLowerCase());

    element.setAttribute("classname", getClass().getName());
    if (exportOptions.contains(ExportOption.bIncludeVersion)) {
        element.setAttribute("version", com.twinsoft.convertigo.beans.Version.version);
    }//from   w  ww  .j  a v a 2s.co m

    // Storing the database object priority
    element.setAttribute("priority", new Long(priority).toString());

    int len;
    PropertyDescriptor[] propertyDescriptors;
    PropertyDescriptor propertyDescriptor;
    Element propertyElement;

    try {
        BeanInfo bi = CachedIntrospector.getBeanInfo(getClass());
        propertyDescriptors = bi.getPropertyDescriptors();
        len = propertyDescriptors.length;
        if (exportOptions.contains(ExportOption.bIncludeDisplayName)) {
            element.setAttribute("displayName", bi.getBeanDescriptor().getDisplayName());
        }
    } catch (IntrospectionException e) {
        throw new EngineException("Couldn't introspect the bean \"" + getName() + "\"", e);
    }

    for (int i = 0; i < len; i++) {
        propertyDescriptor = propertyDescriptors[i];
        String name = propertyDescriptor.getName();
        String displayName = propertyDescriptor.getDisplayName();
        String shortDescription = propertyDescriptor.getShortDescription();

        Method getter = propertyDescriptor.getReadMethod();

        // Only analyze read propertyDescriptors.
        if (getter == null) {
            continue;
        }

        if (checkBlackListParentClass(propertyDescriptor)) {
            continue;
        }

        try {
            // Storing the database object bean properties
            Object uncompiledValue = getCompilablePropertySourceValue(name);
            Object compiledValue = null;
            Object cypheredValue = null;
            Object value = getter.invoke(this);

            if (uncompiledValue != null) {
                compiledValue = value;
                value = uncompiledValue;
            }

            // Only write non-null values
            if (value == null) {
                Engine.logBeans.warn("Attempting to store null property (\"" + name + "\"); skipping...");
                continue;
            }

            propertyElement = document.createElement("property");
            propertyElement.setAttribute("name", name);

            // Encrypts value if needed
            //if (isCipheredProperty(name) && !this.exportOptions.contains(ExportOption.bIncludeDisplayName)) {
            if (isCipheredProperty(name) && (this.exportOptions.contains(ExportOption.bHidePassword)
                    || !this.exportOptions.contains(ExportOption.bIncludeDisplayName))) {
                cypheredValue = encryptPropertyValue(value);
                if (!value.equals(cypheredValue)) {
                    value = cypheredValue;
                    propertyElement.setAttribute("ciphered", "true");
                }
            }

            // Stores the value
            Node node = null;
            if (exportOptions.contains(ExportOption.bIncludeCompiledValue)) {
                node = XMLUtils.writeObjectToXml(document, value, compiledValue);
            } else {
                node = XMLUtils.writeObjectToXml(document, value);
            }
            propertyElement.appendChild(node);

            // Add visibility for logs
            if (!isTraceableProperty(name)) {
                propertyElement.setAttribute("traceable", "false");
            }

            if (exportOptions.contains(ExportOption.bIncludeBlackListedElements)) {
                Object propertyDescriptorBlackListValue = propertyDescriptor
                        .getValue(MySimpleBeanInfo.BLACK_LIST_NAME);
                if (propertyDescriptorBlackListValue != null && (Boolean) propertyDescriptorBlackListValue) {
                    propertyElement.setAttribute("blackListed", "blackListed");
                }
            }
            if (exportOptions.contains(ExportOption.bIncludeDisplayName)) {
                propertyElement.setAttribute("displayName", displayName);
                propertyElement.setAttribute("isHidden", Boolean.toString(propertyDescriptor.isHidden()));
                propertyElement.setAttribute("isMasked",
                        isMaskedProperty(Visibility.Platform, name) ? "true" : "false");
                propertyElement.setAttribute("isExpert", Boolean.toString(propertyDescriptor.isExpert()));
            }
            if (exportOptions.contains(ExportOption.bIncludeShortDescription)) {
                propertyElement.setAttribute("shortDescription", shortDescription);
            }

            if (exportOptions.contains(ExportOption.bIncludeEditorClass)) {
                Class<?> pec = propertyDescriptor.getPropertyEditorClass();
                String message = "";
                if (pec != null) {
                    message = propertyDescriptor.getPropertyEditorClass().toString().replaceFirst("(.)*\\.",
                            "");
                } else {
                    message = "null";
                }
                if (this instanceof ITagsProperty || (pec != null && Enum.class.isAssignableFrom(pec))) {
                    String[] sResults = null;
                    try {
                        if (this instanceof ITagsProperty) {
                            sResults = ((ITagsProperty) this).getTagsForProperty(name);
                        } else {
                            sResults = EnumUtils.toNames(pec);
                        }
                    } catch (Exception ex) {
                        sResults = new String[0];
                    }

                    if (sResults != null) {
                        if (sResults.length > 0) {
                            Element possibleValues = document.createElement("possibleValues");
                            Element possibleValue = null;
                            for (int j = 0; j < sResults.length; j++) {
                                possibleValue = document.createElement("value");
                                possibleValue.setTextContent(sResults[j]);
                                possibleValues.appendChild(possibleValue);
                            }
                            propertyElement.appendChild(possibleValues);
                        }
                    }
                }
                propertyElement.setAttribute("editorClass", message);
            }

            element.appendChild(propertyElement);

            if (Boolean.TRUE.equals(propertyDescriptor.getValue("nillable"))) {
                try {
                    Method method = this.getClass().getMethod("isNullProperty", new Class[] { String.class });
                    Object isNull = method.invoke(this, new Object[] { name });
                    propertyElement.setAttribute("isNull", isNull.toString());
                } catch (Exception ex) {
                    Engine.logBeans.error(
                            "[Serialization] Skipping 'isNull' attribute for property \"" + name + "\".", ex);
                }
            }
        } catch (Exception e) {
            Engine.logBeans.error("[Serialization] Skipping property \"" + name + "\".", e);
        }
    }

    return element;
}

From source file:BeanArrayList.java

/**
 * performs a selection sort on all the beans in the ArrayList by
 * PropertyName/*  ww  w .  ja v a2  s.  c  o  m*/
 *
 * <p>You can use a mixture of bean classes as long as all the beans
 * support the same property (getName() for instance), and all have the
 * same return type, or can be compareTo()ed each other.</p>
 *
 * <p>For optimal performance, it is recommended that if you have a
 * mixed class set the you have them grouped with like classes together
 * as this will minimize reflection inspections.</p>
 * @param propertyName String value containing the property to sort on.
 * @param ascending == sorts up if true, down if not.
 * @throws java.lang.IllegalAccessException reflection exception
 * @throws java.beans.IntrospectionException reflection exception
 * @throws java.lang.reflect.InvocationTargetException reflection exception
 */
public synchronized void sortOnProperty(String propertyName, boolean ascending)
        throws java.lang.IllegalAccessException, java.beans.IntrospectionException,
        java.lang.reflect.InvocationTargetException {
    T[] old = null;

    if ((this.indexPropertyName != null) && (this.changes != null)) {
        old = this.toTypedArray();
    }

    T temp = null;
    String currentClass = "";
    PropertyDescriptor pd = null;
    HashMap cache = new HashMap();

    for (int i = 0; i < (this.size() - 1); i++) {
        for (int j = i + 1; j < this.size(); j++) {
            T o1 = this.get(i);

            if (!currentClass.equals(o1.getClass().getName())) {
                pd = (PropertyDescriptor) cache.get(o1.getClass().getName());

                if (pd == null) {
                    PropertyDescriptor[] pds = Introspector.getBeanInfo(o1.getClass()).getPropertyDescriptors();
                    boolean foundProperty = false;

                    for (int pdi = 0; (pdi < pds.length) && !foundProperty; pdi++) {
                        if (pds[pdi].getName().equals(propertyName)) {
                            pd = pds[pdi];
                            cache.put(o1.getClass().getName(), pd);
                            foundProperty = true;
                        }
                    }
                }
            }

            //System.out.println( "o1: "+o1+" "+pd);
            //System.out.println( propertyName +" "+ (pd == null ));
            Comparable oc1 = (Comparable) pd.getReadMethod().invoke(o1);

            T o2 = this.get(j);

            if (!currentClass.equals(o2.getClass().getName())) {
                pd = (PropertyDescriptor) cache.get(o2.getClass().getName());

                if (pd == null) {
                    PropertyDescriptor[] pds = Introspector.getBeanInfo(o2.getClass()).getPropertyDescriptors();
                    boolean foundProperty = false;

                    for (int pdi = 0; (pdi < pds.length) && !foundProperty; pdi++) {
                        if (pds[pdi].getName().equals(propertyName)) {
                            pd = pds[pdi];
                            foundProperty = true;
                        }
                    }
                }
            }

            Comparable oc2 = (Comparable) pd.getReadMethod().invoke(o2);

            if (ascending) {
                if ((oc1 != oc2)
                        && ((oc2 == null) || ((oc1 != null) && (oc2 != null) && (oc2.compareTo(oc1) < 0)))) { //swap
                    this.setElementAt(o2, i);
                    this.setElementAt(o1, j);
                }
            } else {
                if ((oc1 != oc2)
                        && ((oc1 == null) || ((oc1 != null) && (oc2 != null) && (oc1.compareTo(oc2) < 0)))) { //swap
                    this.setElementAt(o2, i);
                    this.setElementAt(o1, j);
                }
            }
        }

        if (old != null) {
            changes.firePropertyChange(this.indexPropertyName, old, this.toTypedArray());
        }
    }
}

From source file:BeanVector.java

/**
 * performs a selection sort on all the beans in the Vector by
 * PropertyName/*w  w w . j  a v a 2  s .  co  m*/
 *
 * <p>You can use a mixture of bean classes as long as all the beans
 * support the same property (getName() for instance), and all have the
 * same return type, or can be compareTo()ed each other.</p>
 *
 * <p>For optimal performance, it is recommended that if you have a
 * mixed class set the you have them grouped with like classes together
 * as this will minimize reflection inspections.</p>
 * @param propertyName String value containing the property to sort on.
 * @param ascending == sorts up if true, down if not.
 * @throws java.lang.IllegalAccessException reflection exception
 * @throws java.beans.IntrospectionException reflection exception
 * @throws java.lang.reflect.InvocationTargetException reflection exception
 */
public synchronized void sortOnProperty(String propertyName, boolean ascending)
        throws java.lang.IllegalAccessException, java.beans.IntrospectionException,
        java.lang.reflect.InvocationTargetException {
    T[] old = null;

    if ((this.indexPropertyName != null) && (this.changes != null)) {
        old = this.toTypedArray();
    }

    T temp = null;
    String currentClass = "";
    PropertyDescriptor pd = null;
    Hashtable cache = new Hashtable();

    for (int i = 0; i < (this.size() - 1); i++) {
        for (int j = i + 1; j < this.size(); j++) {
            T o1 = this.elementAt(i);

            if (!currentClass.equals(o1.getClass().getName())) {
                pd = (PropertyDescriptor) cache.get(o1.getClass().getName());

                if (pd == null) {
                    PropertyDescriptor[] pds = Introspector.getBeanInfo(o1.getClass()).getPropertyDescriptors();
                    boolean foundProperty = false;

                    for (int pdi = 0; (pdi < pds.length) && !foundProperty; pdi++) {
                        if (pds[pdi].getName().equals(propertyName)) {
                            pd = pds[pdi];
                            cache.put(o1.getClass().getName(), pd);
                            foundProperty = true;
                        }
                    }
                }
            }

            //System.out.println( "o1: "+o1+" "+pd);
            //System.out.println( propertyName +" "+ (pd == null ));
            Comparable oc1 = (Comparable) pd.getReadMethod().invoke(o1);

            T o2 = this.elementAt(j);

            if (!currentClass.equals(o2.getClass().getName())) {
                pd = (PropertyDescriptor) cache.get(o2.getClass().getName());

                if (pd == null) {
                    PropertyDescriptor[] pds = Introspector.getBeanInfo(o2.getClass()).getPropertyDescriptors();
                    boolean foundProperty = false;

                    for (int pdi = 0; (pdi < pds.length) && !foundProperty; pdi++) {
                        if (pds[pdi].getName().equals(propertyName)) {
                            pd = pds[pdi];
                            foundProperty = true;
                        }
                    }
                }
            }

            Comparable oc2 = (Comparable) pd.getReadMethod().invoke(o2);

            if (ascending) {
                if ((oc1 != oc2)
                        && ((oc2 == null) || ((oc1 != null) && (oc2 != null) && (oc2.compareTo(oc1) < 0)))) { //swap
                    this.setElementAt(o2, i);
                    this.setElementAt(o1, j);
                }
            } else {
                if ((oc1 != oc2)
                        && ((oc1 == null) || ((oc1 != null) && (oc2 != null) && (oc1.compareTo(oc2) < 0)))) { //swap
                    this.setElementAt(o2, i);
                    this.setElementAt(o1, j);
                }
            }
        }

        if (old != null) {
            changes.firePropertyChange(this.indexPropertyName, old, this.toTypedArray());
        }
    }
}

From source file:com.hiperf.common.ui.server.storage.impl.PersistenceHelper.java

private static Object deproxyObject(Class<?> targetClass, Object proxy)
        throws InstantiationException, IllegalAccessException, IntrospectionException,
        InvocationTargetException, PersistenceException, ClassNotFoundException {
    Object target = targetClass.newInstance();
    PropertyDescriptor[] targetPds = Introspector.getBeanInfo(targetClass).getPropertyDescriptors();
    for (PropertyDescriptor targetPd : targetPds) {
        if (targetPd.getReadMethod() != null && targetPd.getWriteMethod() != null) {
            Object o = targetPd.getReadMethod().invoke(proxy, new Object[0]);
            if (o != null) {
                Class<?> propertyType = targetPd.getPropertyType();
                String className = propertyType.getName();
                if (!propertyType.isPrimitive() && !o.getClass().isPrimitive() && !(o instanceof Date)
                        && isProxy(o, className)) {
                    if (Set.class.isAssignableFrom(propertyType)) {
                        o = new LazySet();
                    } else if (List.class.isAssignableFrom(propertyType)) {
                        o = new LazyList();
                    } else
                        o = newLazyObject(propertyType);
                }/*w  w w. j  a  v a  2 s. co m*/
                targetPd.getWriteMethod().invoke(target, o);
            }
        }
    }

    return target;
}

From source file:eu.qualityontime.commons.QPropertyUtilsBean.java

/**
 * <p>/*from ww  w  .  j av  a  2  s  . c o m*/
 * Return an accessible property getter method for this property, if there
 * is one; otherwise return <code>null</code>.
 * </p>
 *
 * <p>
 * <strong>FIXME</strong> - Does not work with DynaBeans.
 * </p>
 *
 * @param descriptor
 *            Property descriptor to return a getter for
 * @return The read method
 */
public Method getReadMethod(final PropertyDescriptor descriptor) {

    return MethodUtils.getAccessibleMethod(descriptor.getReadMethod());

}

From source file:eu.qualityontime.commons.QPropertyUtilsBean.java

/**
 * <p>/*w  w  w .  j ava  2  s  .  co  m*/
 * Return an accessible property getter method for this property, if there
 * is one; otherwise return <code>null</code>.
 * </p>
 *
 * <p>
 * <strong>FIXME</strong> - Does not work with DynaBeans.
 * </p>
 *
 * @param clazz
 *            The class of the read method will be invoked on
 * @param descriptor
 *            Property descriptor to return a getter for
 * @return The read method
 */
Method getReadMethod(final Class<?> clazz, final PropertyDescriptor descriptor) {

    return MethodUtils.getAccessibleMethod(clazz, descriptor.getReadMethod());
}