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:com.swingtech.commons.testing.JavaBeanTester.java

/**
 * Tests the get/set methods of the specified class.
 * //from ww  w .  j a  v  a2 s .co  m
 * @param <T> the type parameter associated with the class under test
 * @param clazz the Class under test
 * @param skipThese the names of any properties that should not be tested
 * @throws IntrospectionException thrown if the Introspector.getBeanInfo() method throws this exception 
 * for the class under test
 */
public static <T> void test(final Class<T> clazz, final String... skipThese) throws IntrospectionException {
    final PropertyDescriptor[] props = Introspector.getBeanInfo(clazz).getPropertyDescriptors();
    nextProp: for (PropertyDescriptor prop : props) {
        // Check the list of properties that we don't want to test
        for (String skipThis : skipThese) {
            if (skipThis.equals(prop.getName())) {
                continue nextProp;
            }
        }
        final Method getter = prop.getReadMethod();
        final Method setter = prop.getWriteMethod();

        if (getter != null && setter != null) {
            // We have both a get and set method for this property
            final Class<?> returnType = getter.getReturnType();
            final Class<?>[] params = setter.getParameterTypes();

            if (params.length == 1 && params[0] == returnType) {
                // The set method has 1 argument, which is of the same type as the return type of the get method, so we can test this property
                try {
                    // Build a value of the correct type to be passed to the set method
                    Object value = buildValue(returnType);

                    // Build an instance of the bean that we are testing (each property test gets a new instance)
                    T bean = clazz.newInstance();

                    // Call the set method, then check the same value comes back out of the get method
                    setter.invoke(bean, value);

                    final Object expectedValue = value;
                    final Object actualValue = getter.invoke(bean);

                    assertEquals(String.format("Failed while testing property %s", prop.getName()),
                            expectedValue, actualValue);

                } catch (Exception ex) {
                    fail(String.format("An exception was thrown while testing the property %s: %s",
                            prop.getName(), ex.toString()));
                }
            }
        }
    }
}

From source file:net.sf.ij_plugins.util.DialogUtil.java

/**
 * Utility to automatically create ImageJ's GenericDialog for editing bean properties. It uses BeanInfo to extract
 * display names for each field. If a fields type is not supported irs name will be displayed with a tag
 * "[Unsupported type: class_name]"./*from   w w w  .jav a 2 s  .co  m*/
 *
 * @param bean
 * @return <code>true</code> if user closed bean dialog using OK button, <code>false</code> otherwise.
 */
static public boolean showGenericDialog(final Object bean, final String title) {
    final BeanInfo beanInfo;
    try {
        beanInfo = Introspector.getBeanInfo(bean.getClass());
    } catch (IntrospectionException e) {
        throw new IJPluginsRuntimeException("Error extracting bean info.", e);
    }

    final GenericDialog genericDialog = new GenericDialog(title);

    // Create generic dialog fields for each bean's property
    final PropertyDescriptor[] propertyDescriptors = beanInfo.getPropertyDescriptors();
    try {
        for (int i = 0; i < propertyDescriptors.length; i++) {
            final PropertyDescriptor pd = propertyDescriptors[i];
            final Class type = pd.getPropertyType();
            if (type.equals(Class.class) && "class".equals(pd.getName())) {
                continue;
            }

            final Object o = PropertyUtils.getSimpleProperty(bean, pd.getName());
            if (type.equals(Boolean.TYPE)) {
                boolean value = ((Boolean) o).booleanValue();
                genericDialog.addCheckbox(pd.getDisplayName(), value);
            } else if (type.equals(Integer.TYPE)) {
                int value = ((Integer) o).intValue();
                genericDialog.addNumericField(pd.getDisplayName(), value, 0);
            } else if (type.equals(Float.TYPE)) {
                double value = ((Float) o).doubleValue();
                genericDialog.addNumericField(pd.getDisplayName(), value, 6, 10, "");
            } else if (type.equals(Double.TYPE)) {
                double value = ((Double) o).doubleValue();
                genericDialog.addNumericField(pd.getDisplayName(), value, 6, 10, "");
            } else {
                genericDialog.addMessage(pd.getDisplayName() + "[Unsupported type: " + type + "]");
            }

        }
    } catch (IllegalAccessException e) {
        throw new IJPluginsRuntimeException(e);
    } catch (InvocationTargetException e) {
        throw new IJPluginsRuntimeException(e);
    } catch (NoSuchMethodException e) {
        throw new IJPluginsRuntimeException(e);
    }

    //        final Panel helpPanel = new Panel();
    //        helpPanel.setLayout(new FlowLayout(FlowLayout.LEFT, 5, 0));
    //        final Button helpButton = new Button("Help");
    ////                helpButton.addActionListener(this);
    //        helpPanel.add(helpButton);
    //        genericDialog.addPanel(helpPanel, GridBagConstraints.EAST, new Insets(15,0,0,0));

    // Show modal dialog
    genericDialog.showDialog();
    if (genericDialog.wasCanceled()) {
        return false;
    }

    // Read fields from generic dialog into bean's properties.
    try {
        for (int i = 0; i < propertyDescriptors.length; i++) {
            final PropertyDescriptor pd = propertyDescriptors[i];
            final Class type = pd.getPropertyType();
            final Object propertyValue;
            if (type.equals(Boolean.TYPE)) {
                boolean value = genericDialog.getNextBoolean();
                propertyValue = Boolean.valueOf(value);
            } else if (type.equals(Integer.TYPE)) {
                int value = (int) Math.round(genericDialog.getNextNumber());
                propertyValue = new Integer(value);
            } else if (type.equals(Float.TYPE)) {
                double value = genericDialog.getNextNumber();
                propertyValue = new Float(value);
            } else if (type.equals(Double.TYPE)) {
                double value = genericDialog.getNextNumber();
                propertyValue = new Double(value);
            } else {
                continue;
            }
            PropertyUtils.setProperty(bean, pd.getName(), propertyValue);
        }
    } catch (IllegalAccessException e) {
        throw new IJPluginsRuntimeException(e);
    } catch (InvocationTargetException e) {
        throw new IJPluginsRuntimeException(e);
    } catch (NoSuchMethodException e) {
        throw new IJPluginsRuntimeException(e);
    }

    return true;
}

From source file:org.agnitas.service.csv.Toolkit.java

/**
 * Returns a property descriptor for a named property of a bean.
 *
 * @param bean         The bean to retrieve the property descriptor for
 * @param propertyName The name of the property to find.
 * @return A <code>PropertyDescriptor</code> for the named property or <code>null</code> if no matching property could
 *         be found/*from www . j  a v a 2 s  .  co  m*/
 * @throws IntrospectionException
 */
public static PropertyDescriptor getPropertyDescriptor(Object bean, String propertyName)
        throws IntrospectionException {
    if ((bean == null) || (propertyName == null)) {
        return null;
    }

    PropertyDescriptor[] propertyDescriptors = Introspector.getBeanInfo(bean.getClass())
            .getPropertyDescriptors();
    for (PropertyDescriptor propertyDescriptor : propertyDescriptors) {
        if (propertyName.equals(propertyDescriptor.getName())) {
            return propertyDescriptor;
        }
    }
    //if property description doesn't found return customFields HashMap
    try {
        return PropertyUtils.getPropertyDescriptor(bean, "customFields");
    } catch (Exception e) {
        AgnUtils.logger().error("Retriving of bean descriptor failed", e);
    }

    return null;
}

From source file:therian.util.BeanProperties.java

public static Set<String> getPropertyNames(ReturnProperties returnProperties, TherianContext context,
        Position.Readable<?> position) {

    List<? extends FeatureDescriptor> descriptors;
    // first try ELResolver:

    try {//from   w w  w.j av  a  2s. c  om
        descriptors = IteratorUtils
                .toList(context.getELResolver().getFeatureDescriptors(context, position.getValue()));
    } catch (Exception e) {
        descriptors = null;
    }

    if (CollectionUtils.isEmpty(descriptors)) {
        // java.beans introspection; on RT type if available, else raw position type:
        final Class<?> beanType;
        if (position.getValue() == null) {
            beanType = TypeUtils.getRawType(position.getType(), null);
        } else {
            beanType = position.getValue().getClass();
        }
        try {
            descriptors = Arrays.asList(Introspector.getBeanInfo(beanType).getPropertyDescriptors());
        } catch (IntrospectionException e1) {
            return Collections.emptySet();
        }
    }

    final Set<String> result = new HashSet<>();
    for (final FeatureDescriptor fd : descriptors) {
        final String name = fd.getName();
        if (returnProperties == ReturnProperties.WRITABLE) {
            try {
                if (context.getELResolver().isReadOnly(context, position.getValue(), name)) {
                    continue;
                }
            } catch (Exception e) {
                // if we can't even _check_ for readOnly, assume not writable:
                continue;
            }
        }
        result.add(name);
    }
    return result;
}

From source file:org.apache.niolex.commons.bean.BeanUtil.java

/**
 * Merge the non null properties from the source bean to the target bean.
 *
 * @param to the target bean/*from  www . j  a  v a 2 s.c o  m*/
 * @param from the source bean
 * @param mergeDefault whether do we merge default numeric primitives
 * @return the target bean
 */
public static final <To, From> To merge(To to, From from, boolean mergeDefault) {
    try {
        Map<String, Method> writeMap = prepareWriteMethodMap(to.getClass());
        BeanInfo fromInfo = Introspector.getBeanInfo(from.getClass());
        // Iterate over all the attributes of from, do copy here.
        for (PropertyDescriptor descriptor : fromInfo.getPropertyDescriptors()) {
            Method readMethod = descriptor.getReadMethod();
            if (readMethod == null) {
                continue;
            }
            Method writeMethod = writeMap.get(descriptor.getName());
            if (writeMethod == null) {
                continue;
            }
            Object value = readMethod.invoke(from);
            if (value == null) {
                continue;
            }
            if (!mergeDefault && isNumericPrimitiveDefaultValue(readMethod.getReturnType(), value)) {
                continue;
            }
            // Only copy value if it's assignable, auto boxing is OK.
            if (ClassUtils.isAssignable(value.getClass(), writeMethod.getParameterTypes()[0], true)) {
                writeMethod.invoke(to, value);
            }
        }
    } catch (Exception e) {
        throw new IllegalArgumentException("Failed to merge propeties.", e);
    }
    return to;
}

From source file:org.senro.metadata.AOPMetadataManagerTest.java

/**
 * Test that the metadata recovery for the Class is correct
 * @throws Exception/*from w  w w . j a  va  2  s .c om*/
 */
public void testMetadataClass() throws Exception {
    Metadata result = metadataManager.getMetadata(A.class);
    BeanInfo beanInfo = Introspector.getBeanInfo(A.class);
    assertEquals("correct metadata retrieval", A.class, ((ReflectionMetadataClass) result).getType());
    assertEquals("properties copy for reflective", beanInfo.getBeanDescriptor().getDisplayName(),
            ((ReflectionMetadataClass) result).getDisplayName());
}

From source file:org.dspace.app.rest.link.DSpaceResourceHalLinkFactory.java

protected void addLinks(DSpaceResource halResource, Pageable page, LinkedList<Link> list) throws Exception {
    RestAddressableModel data = halResource.getContent();

    try {/*from w ww  .j a v a  2 s  . c  o m*/
        for (PropertyDescriptor pd : Introspector.getBeanInfo(data.getClass()).getPropertyDescriptors()) {
            Method readMethod = pd.getReadMethod();
            String name = pd.getName();
            if (readMethod != null && !"class".equals(name)) {
                LinkRest linkAnnotation = readMethod.getAnnotation(LinkRest.class);

                if (linkAnnotation != null) {
                    if (StringUtils.isNotBlank(linkAnnotation.name())) {
                        name = linkAnnotation.name();
                    }

                    Link linkToSubResource = utils.linkToSubResource(data, name);
                    // no method is specified to retrieve the linked object(s) so check if it is already here
                    if (StringUtils.isBlank(linkAnnotation.method())) {
                        Object linkedObject = readMethod.invoke(data);

                        if (linkedObject instanceof RestAddressableModel
                                && linkAnnotation.linkClass().isAssignableFrom(linkedObject.getClass())) {
                            linkToSubResource = utils.linkToSingleResource((RestAddressableModel) linkedObject,
                                    name);
                        }

                        if (linkedObject != null || !linkAnnotation.optional()) {
                            halResource.add(linkToSubResource);
                        }
                    }

                } else if (RestModel.class.isAssignableFrom(readMethod.getReturnType())) {
                    Link linkToSubResource = utils.linkToSubResource(data, name);
                    halResource.add(linkToSubResource);
                }
            }
        }
    } catch (IntrospectionException e) {
        e.printStackTrace();
    }

    halResource.add(utils.linkToSingleResource(data, Link.REL_SELF));
}

From source file:com.ebay.pulsar.analytics.dao.mapper.BaseDBMapper.java

@SuppressWarnings("unchecked")
@Override// www  .j  a  v  a 2s .c  o m
public T mapRow(ResultSet r, int index) throws SQLException {
    try {
        T obj = (T) clazz.newInstance();
        if (obj == null) {
            return null;
        }
        try {

            BeanInfo beanInfo = Introspector.getBeanInfo(clazz);
            PropertyDescriptor[] propertyDescriptors = beanInfo.getPropertyDescriptors();
            for (PropertyDescriptor property : propertyDescriptors) {
                String key = property.getName();
                if (!key.equals("class")) {
                    Object value = null;
                    try {
                        Method setter = property.getWriteMethod();
                        value = r.getObject(key.toLowerCase());
                        if (value != null && value instanceof Number) {
                            @SuppressWarnings("rawtypes")
                            Class[] types = setter.getParameterTypes();
                            value = NumberUtils.convertNumberToTargetClass((Number) value, types[0]);
                        }
                        if (value != null) {
                            if (value.getClass().equals(BigInteger.class)) {
                                setter.invoke(obj, ((BigInteger) value).longValue());
                            } else if (value.getClass().equals(byte[].class)) {
                                setter.invoke(obj, new String((byte[]) value));
                            } else if (Blob.class.isAssignableFrom(value.getClass())) {
                                Blob bv = (Blob) value;
                                byte[] b = new byte[(int) bv.length()];
                                InputStream stream = bv.getBinaryStream();
                                stream.read(b);
                                stream.close();
                                String v = new String(b);
                                setter.invoke(obj, v);
                            } else {
                                setter.invoke(obj, value);
                            }
                        }
                    } catch (Exception e) {
                        logger.error("transBean2Map Error " + e);
                        logger.error("name[" + key + "]=" + (value == null ? "NULL" : value.toString())
                                + ", class:" + (value == null ? "NULL" : value.getClass()) + ", err:"
                                + e.getMessage());
                    }

                }

            }
        } catch (Exception e) {
            logger.error("transBean2Map Error " + e);
        }
        return obj;
    } catch (Exception e) {
        logger.error("Exception:" + e);
    }

    return null;
}

From source file:org.parancoe.validator.constraints.impl.NewPasswordValidator.java

@Override
public boolean isValid(Object value, ConstraintValidatorContext context) {
    String newPasswordValue = null;
    String confirmPasswordValue = null;
    boolean newPasswordFound = false;
    boolean confirmPasswordFound = false;
    try {//w w w.ja va 2 s .co m
        BeanInfo beanInfo = Introspector.getBeanInfo(value.getClass());
        PropertyDescriptor[] propertyDescriptors = beanInfo.getPropertyDescriptors();
        for (PropertyDescriptor propertyDescriptor : propertyDescriptors) {
            if (constraintAnnotation.newPasswordProperty().equals(propertyDescriptor.getName())) {
                newPasswordValue = (String) propertyDescriptor.getReadMethod().invoke(value);
                newPasswordFound = true;
            }
            if (constraintAnnotation.confirmPasswordProperty().equals(propertyDescriptor.getName())) {
                confirmPasswordValue = (String) propertyDescriptor.getReadMethod().invoke(value);
                confirmPasswordFound = true;
            }
            if (newPasswordFound && confirmPasswordFound) {
                break;
            }
        }
    } catch (Exception ex) {
        throw new RuntimeException("Can't validate this bean.", ex);
    }
    if (!newPasswordFound) {
        throw new RuntimeException("Can't validate this bean: property "
                + constraintAnnotation.newPasswordProperty() + " not found.");
    }
    if (!confirmPasswordFound) {
        throw new RuntimeException("Can't validate this bean: property "
                + constraintAnnotation.confirmPasswordProperty() + " not found.");
    }
    if (constraintAnnotation.passIfBlank()) {
        if (value == null
                || (StringUtils.isBlank(newPasswordValue) && StringUtils.isBlank(confirmPasswordValue))) {
            return true;
        }
    }
    boolean result = true;
    if (StringUtils.isNotBlank(newPasswordValue) && !newPasswordValue.equals(confirmPasswordValue)) {
        context.disableDefaultConstraintViolation();
        context.buildConstraintViolationWithTemplate("{org.parancoe.validator.constraints.NewPassword.message}")
                .addNode("newPassword").addConstraintViolation().disableDefaultConstraintViolation();
        result = false;
    }
    return result;
}

From source file:stroom.util.AbstractCommandLineTool.java

public void init(final String[] args) throws Exception {
    map = new HeaderMap();
    validArguments = new ArrayList<String>();

    map.loadArgs(args);/* w w w  .  j a va2  s.c o m*/

    final BeanInfo beanInfo = Introspector.getBeanInfo(this.getClass());

    for (final PropertyDescriptor field : beanInfo.getPropertyDescriptors()) {
        if (field.getWriteMethod() != null) {
            if (field.getName().length() > maxPropLength) {
                maxPropLength = field.getName().length();
            }
            if (map.containsKey(field.getName())) {
                validArguments.add(field.getName());
                field.getWriteMethod().invoke(this, getAsType(field));
            }
        }
    }

    checkArgs();
}