Example usage for java.beans Introspector getBeanInfo

List of usage examples for java.beans Introspector getBeanInfo

Introduction

In this page you can find the example usage for java.beans Introspector getBeanInfo.

Prototype

public static BeanInfo getBeanInfo(Class<?> beanClass) throws IntrospectionException 

Source Link

Document

Introspect on a Java Bean and learn about all its properties, exposed methods, and events.

Usage

From source file:org.apache.jcs.config.PropertySetter.java

/**
 * Uses JavaBeans {@link Introspector}to computer setters of object to be
 * configured./* ww w .j  a va  2s .  c o m*/
 */
protected void introspect() {
    try {
        BeanInfo bi = Introspector.getBeanInfo(obj.getClass());
        props = bi.getPropertyDescriptors();
    } catch (IntrospectionException ex) {
        log.error("Failed to introspect " + obj + ": " + ex.getMessage());
        props = new PropertyDescriptor[0];
    }
}

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

/**
 * Performs introspection of a specific Java class. This implementation uses
 * the {@code java.beans.Introspector.getBeanInfo()} method to obtain all
 * property descriptors for the current class and adds them to the passed in
 * introspection context./* www.jav a2 s  .  co m*/
 *
 * @param icontext
 *            the introspection context
 */
@Override
public void introspect(final IntrospectionContext icontext) {
    BeanInfo beanInfo = null;
    try {
        beanInfo = Introspector.getBeanInfo(icontext.getTargetClass());
    } catch (final IntrospectionException e) {
        // no descriptors are added to the context
        log.error("Error when inspecting class " + icontext.getTargetClass(), e);
        return;
    }

    PropertyDescriptor[] descriptors = beanInfo.getPropertyDescriptors();
    if (descriptors == null) {
        descriptors = new PropertyDescriptor[0];
    }

    handleIndexedPropertyDescriptors(icontext.getTargetClass(), descriptors);
    icontext.addPropertyDescriptors(descriptors);
}

From source file:org.lambdamatic.internal.elasticsearch.codec.DocumentCodec.java

/**
 * Constructor.//from  w w  w. j a v a  2 s. c  o m
 * 
 * @param domainType The domain type to encode/decode. Must be annotated with {@link Document} or
 *        {@link EmbeddedDocument}
 * @param objectMapper the {@link ObjectMapper} to encode/decode documents
 * @throws DomainTypeException if an exception occurs during introspection of the given domain
 *         type.
 */
public DocumentCodec(final Class<T> domainType, final ObjectMapper objectMapper) throws DomainTypeException {
    this.domainType = domainType;
    this.objectMapper = objectMapper;
    try {
        this.domainTypeBeanInfo = Introspector.getBeanInfo(domainType);
    } catch (IntrospectionException e) {
        throw new DomainTypeException("Failed to analyse domain type '" + domainType.getName() + "'", e);
    }
}

From source file:com.searchbox.core.search.AbstractSearchCondition.java

@Override
public boolean equals(Object other) {
    if (!this.getClass().equals(other.getClass())) {
        return false;
    } else {/*w  ww  .ja  v  a  2  s . co m*/
        try {
            for (PropertyDescriptor propertyDescriptor : Introspector.getBeanInfo(this.getClass())
                    .getPropertyDescriptors()) {

                Method method = propertyDescriptor.getReadMethod();
                Object res1 = method.invoke(this);
                Object res2 = method.invoke(other);

                if ((res1 == null && res2 != null) || (res1 != null && res2 == null)) {
                    return false;
                }
                if (res1 != null && res2 != null && !res1.equals(res2)) {
                    return false;
                }
            }
        } catch (Exception e) {
            LOGGER.error("Could not compare Objects", e);
            return false;
        }
    }
    return true;
}

From source file:org.apache.syncope.core.misc.jexl.JexlUtils.java

public static JexlContext addFieldsToContext(final Object object, final JexlContext jexlContext) {
    JexlContext context = jexlContext == null ? new MapContext() : jexlContext;

    try {/*  www . j  a  v  a2  s  .  c om*/
        for (PropertyDescriptor desc : Introspector.getBeanInfo(object.getClass()).getPropertyDescriptors()) {
            Class<?> type = desc.getPropertyType();
            String fieldName = desc.getName();

            if ((!fieldName.startsWith("pc")) && (!ArrayUtils.contains(IGNORE_FIELDS, fieldName))
                    && (!Iterable.class.isAssignableFrom(type)) && (!type.isArray())) {

                try {
                    Object fieldValue;
                    if (desc.getReadMethod() == null) {
                        final Field field = object.getClass().getDeclaredField(fieldName);
                        field.setAccessible(true);
                        fieldValue = field.get(object);
                    } else {
                        fieldValue = desc.getReadMethod().invoke(object);
                    }

                    context.set(fieldName,
                            fieldValue == null ? StringUtils.EMPTY
                                    : (type.equals(Date.class) ? DataFormat.format((Date) fieldValue, false)
                                            : fieldValue));

                    LOG.debug("Add field {} with value {}", fieldName, fieldValue);
                } catch (Exception iae) {
                    LOG.error("Reading '{}' value error", fieldName, iae);
                }
            }
        }
    } catch (IntrospectionException ie) {
        LOG.error("Reading class attributes error", ie);
    }

    if (object instanceof Any) {
        Any<?, ?, ?> any = (Any<?, ?, ?>) object;
        if (any.getRealm() != null) {
            context.set("realm", any.getRealm().getName());
        }
    }

    return context;
}

From source file:org.lnicholls.galleon.gui.HMEConfigurationPanel.java

public HMEConfigurationPanel(Object bean) {

    setLayout(new GridLayout(0, 1));

    target = bean;/*from ww w  .ja  v  a2s . c  om*/

    try {

        BeanInfo bi = Introspector.getBeanInfo(target.getClass());

        properties = bi.getPropertyDescriptors();

    } catch (IntrospectionException ex) {

        Tools.logException(HMEConfigurationPanel.class, ex, "PropertySheet: Couldn't introspect");

        return;

    }

    editors = new PropertyEditor[properties.length];

    values = new Object[properties.length];

    views = new Component[properties.length];

    labels = new JLabel[properties.length];

    for (int i = 0; i < properties.length; i++) {

        // Don't display hidden or expert properties.

        if (properties[i].isHidden() || properties[i].isExpert()) {

            continue;

        }

        String name = properties[i].getDisplayName();

        Class type = properties[i].getPropertyType();

        Method getter = properties[i].getReadMethod();

        Method setter = properties[i].getWriteMethod();

        // Only display read/write properties.

        if (getter == null || setter == null) {

            continue;

        }

        Component view = null;

        try {

            Object args[] = {};

            Object value = getter.invoke(target, args);

            values[i] = value;

            PropertyEditor editor = null;

            Class pec = properties[i].getPropertyEditorClass();

            if (pec != null) {

                try {

                    editor = (PropertyEditor) pec.newInstance();

                } catch (Exception ex) {

                    // Drop through.

                }

            }

            if (editor == null) {

                editor = PropertyEditorManager.findEditor(type);

            }

            editors[i] = editor;

            // If we can't edit this component, skip it.

            if (editor == null) {

                // If it's a user-defined property we give a warning.

                String getterClass = properties[i].getReadMethod().getDeclaringClass().getName();

                if (getterClass.indexOf("java.") != 0) {

                    log.error("Warning: Can't find public property editor for property \"" + name

                            + "\".  Skipping.");

                }

                continue;

            }

            // Don't try to set null values:

            if (value == null) {

                // If it's a user-defined property we give a warning.

                String getterClass = properties[i].getReadMethod().getDeclaringClass().getName();

                if (getterClass.indexOf("java.") != 0) {

                    log.error("Warning: Property \"" + name + "\" has null initial value.  Skipping.");

                }

                continue;

            }

            editor.setValue(value);

            // editor.addPropertyChangeListener(adaptor);

            // Now figure out how to display it...

            if (editor.isPaintable() && editor.supportsCustomEditor()) {

                view = new PropertyCanvas(frame, editor);

            } else if (editor.getTags() != null) {

                view = new PropertySelector(editor);

            } else if (editor.getAsText() != null) {

                String init = editor.getAsText();

                view = new PropertyText(editor);

            } else {

                log.error("Warning: Property \"" + name + "\" has non-displayabale editor.  Skipping.");

                continue;

            }

        } catch (InvocationTargetException ex) {

            Tools.logException(HMEConfigurationPanel.class, ex.getTargetException(),
                    "Skipping property " + name);

            continue;

        } catch (Exception ex) {

            Tools.logException(HMEConfigurationPanel.class, ex, "Skipping property " + name);

            continue;

        }

        labels[i] = new JLabel(WordUtils.capitalize(name), JLabel.RIGHT);

        // add(labels[i]);

        views[i] = view;

        // add(views[i]);

    }

    int validCounter = 0;

    for (int i = 0; i < labels.length; i++) {

        if (labels[i] != null)

            validCounter++;

    }

    String rowStrings = ""; // general

    if (validCounter > 0)

        rowStrings = "pref, ";

    else

        rowStrings = "pref";

    int counter = 0;

    for (int i = 0; i < labels.length; i++) {

        if (labels[i] != null) {

            if (++counter == (validCounter))

                rowStrings = rowStrings + "9dlu, " + "pref";

            else

                rowStrings = rowStrings + "9dlu, " + "pref, ";

        }

    }

    FormLayout layout = new FormLayout("right:pref, 3dlu, 50dlu:g, right:pref:grow", rowStrings);

    PanelBuilder builder = new PanelBuilder(layout);

    //DefaultFormBuilder builder = new DefaultFormBuilder(new FormDebugPanel(), layout);

    builder.setDefaultDialogBorder();

    CellConstraints cc = new CellConstraints();

    builder.addSeparator("General", cc.xyw(1, 1, 4));

    counter = 0;

    for (int i = 0; i < labels.length; i++) {

        if (labels[i] != null) {

            counter++;

            builder.add(labels[i], cc.xy(1, counter * 2 + 1));

            builder.add(views[i], cc.xy(3, counter * 2 + 1));

        }

    }

    JPanel panel = builder.getPanel();

    //FormDebugUtils.dumpAll(panel);

    add(panel);

}

From source file:kelly.util.BeanUtils.java

/**
 * Retrieve the JavaBeans {@code PropertyDescriptor}s of a given class.
 * @param clazz the Class to retrieve the PropertyDescriptors for
 * @return an array of {@code PropertyDescriptors} for the given class
 *///from w  w  w  . j a  v  a2  s. co  m
public static PropertyDescriptor[] getPropertyDescriptors(Class<?> clazz) {
    Validate.notNull(clazz, "Class must not be null");
    try {
        BeanInfo beanInfo = Introspector.getBeanInfo(clazz);
        return beanInfo.getPropertyDescriptors();
    } catch (IntrospectionException e) {
        throw new BeanException(e.getMessage(), e);
    }
}

From source file:org.apache.syncope.core.util.jexl.JexlUtil.java

public static JexlContext addFieldsToContext(final Object attributable, final JexlContext jexlContext) {
    JexlContext context = jexlContext == null ? new MapContext() : jexlContext;

    try {/*from  ww  w .  j av  a 2s .c om*/
        for (PropertyDescriptor desc : Introspector.getBeanInfo(attributable.getClass())
                .getPropertyDescriptors()) {
            final Class<?> type = desc.getPropertyType();
            final String fieldName = desc.getName();

            if ((!fieldName.startsWith("pc")) && (!ArrayUtils.contains(IGNORE_FIELDS, fieldName))
                    && (!Iterable.class.isAssignableFrom(type)) && (!type.isArray())) {
                try {
                    final Method getter = desc.getReadMethod();

                    final Object fieldValue;

                    if (getter == null) {
                        final Field field = attributable.getClass().getDeclaredField(fieldName);
                        field.setAccessible(true);
                        fieldValue = field.get(attributable);
                    } else {
                        fieldValue = getter.invoke(attributable);
                    }

                    context.set(fieldName,
                            fieldValue == null ? ""
                                    : (type.equals(Date.class) ? DataFormat.format((Date) fieldValue, false)
                                            : fieldValue));

                    LOG.debug("Add field {} with value {}", fieldName, fieldValue);

                } catch (Exception iae) {
                    LOG.error("Reading '{}' value error", fieldName, iae);
                }
            }
        }
    } catch (IntrospectionException ie) {
        LOG.error("Reading class attributes error", ie);
    }

    return context;
}

From source file:cn.fql.utility.ClassUtility.java

/**
 * Export property desc of specified class
 *
 * @param beanClass specified class/*  w ww.j a v  a2 s . c om*/
 * @return @see java.beans.BeanInfo#getPropertyDescriptors
 * @throws java.beans.IntrospectionException
 *          if there is exception occurs
 */
public static PropertyDescriptor[] exportPropertyDesc(Class beanClass) throws IntrospectionException {
    BeanInfo bi;
    PropertyDescriptor[] pds;
    bi = Introspector.getBeanInfo(beanClass);
    pds = bi.getPropertyDescriptors();
    return pds;
}

From source file:org.apache.syncope.core.misc.jexl.JexlUtil.java

public static JexlContext addFieldsToContext(final Object object, final JexlContext jexlContext) {
    JexlContext context = jexlContext == null ? new MapContext() : jexlContext;

    try {//  w w w. j a  va2  s  . c  om
        for (PropertyDescriptor desc : Introspector.getBeanInfo(object.getClass()).getPropertyDescriptors()) {
            final Class<?> type = desc.getPropertyType();
            final String fieldName = desc.getName();

            if ((!fieldName.startsWith("pc")) && (!ArrayUtils.contains(IGNORE_FIELDS, fieldName))
                    && (!Iterable.class.isAssignableFrom(type)) && (!type.isArray())) {
                try {
                    final Method getter = desc.getReadMethod();

                    final Object fieldValue;

                    if (getter == null) {
                        final Field field = object.getClass().getDeclaredField(fieldName);
                        field.setAccessible(true);
                        fieldValue = field.get(object);
                    } else {
                        fieldValue = getter.invoke(object);
                    }

                    context.set(fieldName,
                            fieldValue == null ? StringUtils.EMPTY
                                    : (type.equals(Date.class) ? DataFormat.format((Date) fieldValue, false)
                                            : fieldValue));

                    LOG.debug("Add field {} with value {}", fieldName, fieldValue);

                } catch (Exception iae) {
                    LOG.error("Reading '{}' value error", fieldName, iae);
                }
            }
        }
    } catch (IntrospectionException ie) {
        LOG.error("Reading class attributes error", ie);
    }

    return context;
}