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:Main.java

public static void main(String[] argv) throws Exception {

    BeanInfo bi = Introspector.getBeanInfo(MyBean.class);
    PropertyDescriptor[] pds = bi.getPropertyDescriptors();
    for (int i = 0; i < pds.length; i++) {

        String propName = pds[i].getDisplayName();
        System.out.println(propName);
    }//w ww . j  a  v  a 2 s  .  com

}

From source file:Main.java

public static void main(String[] argv) throws Exception {
    BeanInfo beanInfo = Introspector.getBeanInfo(Fruit.class);
    PropertyDescriptor[] pds = beanInfo.getPropertyDescriptors();

    for (PropertyDescriptor pd : pds) {
        String propertyName = pd.getName();
        System.out.println("propertyName = " + propertyName);
    }/*from   w  w  w  .  j  av a2 s.  c  om*/
}

From source file:IntrospectorDemo.java

public static void main(String args[]) {
    try {/*from   w  w  w.ja v a 2 s.  c o m*/
        Class c = Class.forName("Colors");
        BeanInfo beanInfo = Introspector.getBeanInfo(c);

        System.out.println("Properties:");
        PropertyDescriptor propertyDescriptor[] = beanInfo.getPropertyDescriptors();
        for (int i = 0; i < propertyDescriptor.length; i++) {
            System.out.println("\t" + propertyDescriptor[i].getName());
        }

        System.out.println("Events:");
        EventSetDescriptor eventSetDescriptor[] = beanInfo.getEventSetDescriptors();
        for (int i = 0; i < eventSetDescriptor.length; i++) {
            System.out.println("\t" + eventSetDescriptor[i].getName());
        }
    } catch (Exception e) {
        System.out.println("Exception caught. " + e);
    }
}

From source file:Main.java

public static void main(String[] argv) throws Exception {
    BeanInfo bi = Introspector.getBeanInfo(BeanToXmlTransient.class);
    PropertyDescriptor[] pds = bi.getPropertyDescriptors();
    for (int i = 0; i < pds.length; i++) {
        PropertyDescriptor propertyDescriptor = pds[i];
        if (propertyDescriptor.getName().equals("itemQuantities")) {
            propertyDescriptor.setValue("transient", Boolean.TRUE);
        }//from w  w w . j av a2  s.co  m
    }
    BeanToXmlTransient bean = new BeanToXmlTransient();
    bean.setId(new Long(1));
    bean.setItemName("Item");
    bean.setItemColour("Red");
    bean.setItemQuantities(new Integer(100));

    XMLEncoder encoder = new XMLEncoder(new BufferedOutputStream(new FileOutputStream("BeanTransient.xml")));

    encoder.writeObject(bean);
    encoder.close();

}

From source file:generators.ExpressionMetaValidator.java

public static void main(String[] args) {
    ClassicEngineBoot.getInstance().start();
    int invalidExpressionsCounter = 0;
    int deprecatedExpressionsCounter = 0;
    final HashNMap expressionsByGroup = new HashNMap();

    ExpressionRegistry expressionRegistry = ExpressionRegistry.getInstance();
    final ExpressionMetaData[] allExpressions = expressionRegistry.getAllExpressionMetaDatas();
    for (int i = 0; i < allExpressions.length; i++) {
        final ExpressionMetaData expression = allExpressions[i];
        if (expression == null) {
            logger.warn("Null Expression encountered");
            continue;
        }/*from w  w w . j ava  2s. c o m*/

        missingProperties.clear();

        final Class type = expression.getExpressionType();
        if (type == null) {
            logger.warn("Expression class is null");
        }

        logger.debug("Processing " + type);

        final Class resultType = expression.getResultType();
        if (resultType == null) {
            logger.warn("Expression '" + expression.getExpressionType() + " is null");
        }

        try {
            final BeanInfo beanInfo = expression.getBeanDescriptor();
            if (beanInfo == null) {
                logger.warn(
                        "Expression '" + expression.getExpressionType() + ": Cannot get BeanDescriptor: Null");
            }
        } catch (IntrospectionException e) {
            logger.warn("Expression '" + expression.getExpressionType() + ": Cannot get BeanDescriptor", e);
        }

        final Locale locale = Locale.getDefault();
        final String displayName = expression.getDisplayName(locale);
        if (isValid(displayName, expression.getName()) == false) {
            logger.warn("Expression '" + expression.getExpressionType() + ": No valid display name");
        }
        if (expression.isDeprecated()) {
            deprecatedExpressionsCounter += 1;
            final String deprecateMessage = expression.getDeprecationMessage(locale);
            if (isValid(deprecateMessage, "Use a Formula instead") == false) {
                logger.warn("Expression '" + expression.getExpressionType() + ": No valid deprecate message");
            }
        }
        final String grouping = expression.getGrouping(locale);
        if (isValid(grouping, "Group") == false) {
            logger.warn("Expression '" + expression.getExpressionType() + ": No valid grouping message");
        }

        expressionsByGroup.add(grouping, expression);

        final ExpressionPropertyMetaData[] properties = expression.getPropertyDescriptions();
        for (int j = 0; j < properties.length; j++) {
            final ExpressionPropertyMetaData propertyMetaData = properties[j];
            final String name = propertyMetaData.getName();
            if (StringUtils.isEmpty(name)) {
                logger.warn("Expression '" + expression.getExpressionType() + ": Property without a name");
            }
            final String propertyDisplayName = propertyMetaData.getDisplayName(locale);
            if (isValid(propertyDisplayName, name) == false) {
                logger.warn("Expression '" + expression.getExpressionType() + ": Property "
                        + propertyMetaData.getName() + ": No DisplayName");
            }

            final String propertyGrouping = propertyMetaData.getGrouping(locale);
            if (isValid(propertyGrouping, "Group") == false) {
                logger.warn("Expression '" + expression.getExpressionType() + ": Property "
                        + propertyMetaData.getName() + ": Grouping is not valid");
            }
            final int groupingOrdinal = propertyMetaData.getGroupingOrdinal(locale);
            if (groupingOrdinal == Integer.MAX_VALUE) {
                if (propertyMetaData instanceof DefaultExpressionMetaData) {
                    final DefaultExpressionPropertyMetaData demd = (DefaultExpressionPropertyMetaData) propertyMetaData;
                    missingProperties.add(demd.getKeyPrefix() + "grouping.ordinal=1000");
                }
                logger.warn("Expression '" + expression.getExpressionType() + ": Property "
                        + propertyMetaData.getName() + ": Grouping ordinal is not valid");
            }
            final int ordinal = propertyMetaData.getItemOrdinal(locale);
            if (groupingOrdinal == Integer.MAX_VALUE) {
                if (propertyMetaData instanceof DefaultExpressionMetaData) {
                    final DefaultExpressionPropertyMetaData demd = (DefaultExpressionPropertyMetaData) propertyMetaData;
                    missingProperties.add(demd.getKeyPrefix() + "ordinal=1000");
                }
                logger.warn("Expression '" + expression.getExpressionType() + ": Property "
                        + propertyMetaData.getName() + ": Ordinal is not valid");
            }
            final String propertyDescription = propertyMetaData.getDescription(locale);
            if (isValid(propertyDescription, "") == false) {
                logger.warn("Expression '" + expression.getExpressionType() + ": Property "
                        + propertyMetaData.getName() + ": Description is not valid");
            }
            final String propertyDeprecated = propertyMetaData.getDeprecationMessage(locale);
            if (isValid(propertyDeprecated, "") == false) {
                logger.warn("Expression '" + expression.getExpressionType() + ": Property "
                        + propertyMetaData.getName() + ": Deprecation is not valid");
            }

            final String role = propertyMetaData.getPropertyRole();
            if (isValid(role, "Value") == false) {
                logger.warn("Expression '" + expression.getExpressionType() + ": Property "
                        + propertyMetaData.getName() + ": Role is not valid");
            }
            final Class propertyType = propertyMetaData.getPropertyType();
            if (propertyType == null) {
                logger.warn("Expression '" + expression.getExpressionType() + ": Property "
                        + propertyMetaData.getName() + ": Property Type is not valid");
            }

            // should not crash!
            final PropertyDescriptor propertyDescriptor = propertyMetaData.getBeanDescriptor();

            if (propertyMetaData.isDeprecated()) {
                final String deprecateMessage = propertyMetaData.getDeprecationMessage(locale);
                if (isValid(deprecateMessage, "Deprecated") == false) {
                    logger.warn("Expression '" + expression.getExpressionType() + ": Property "
                            + propertyMetaData.getName() + ": No valid deprecate message");
                }
            }

        }

        try {
            final BeanInfo beanInfo = Introspector.getBeanInfo(expression.getExpressionType());
            final PropertyDescriptor[] descriptors = beanInfo.getPropertyDescriptors();
            for (int propIdx = 0; propIdx < descriptors.length; propIdx++) {
                final PropertyDescriptor descriptor = descriptors[propIdx];
                final String key = descriptor.getName();

                if ("runtime".equals(key)) {
                    continue;
                }
                if ("active".equals(key)) {
                    continue;
                }
                if ("preserve".equals(key)) {
                    continue;
                }

                if (descriptor.getReadMethod() == null || descriptor.getWriteMethod() == null) {
                    continue;
                }

                if (expression.getPropertyDescription(key) == null) {
                    logger.warn("Expression '" + expression.getExpressionType()
                            + ": No property definition for " + key);
                    missingPropertyDefs.add("    <property name=\"" + key
                            + "\" mandatory=\"false\" preferred=\"false\" value-role=\"Value\" expert=\"false\" hidden=\"false\"/>");
                }
            }

        } catch (Throwable e) {
            logger.warn("Expression '" + expression.getExpressionType() + ": Cannot get BeanDescriptor", e);
        }

        System.err.flush();
        try {
            Thread.sleep(25);
        } catch (InterruptedException e) {
        }

        for (int x = 0; x < missingProperties.size(); x++) {
            final String property = (String) missingProperties.get(x);
            System.out.println(property);
        }

        for (int j = 0; j < missingPropertyDefs.size(); j++) {
            final String def = (String) missingPropertyDefs.get(j);
            System.out.println(def);
        }

        if (missingProperties.isEmpty() == false || missingPropertyDefs.isEmpty() == false) {
            invalidExpressionsCounter += 1;
            missingProperties.clear();
            missingPropertyDefs.clear();
        }
        System.out.flush();
        try {
            Thread.sleep(25);
        } catch (InterruptedException e) {
        }
    }

    logger.info("Validated " + allExpressions.length + " expressions. Invalid: " + invalidExpressionsCounter
            + " Deprecated: " + deprecatedExpressionsCounter);

    final Object[] keys = expressionsByGroup.keySet().toArray();
    Arrays.sort(keys);
    for (int i = 0; i < keys.length; i++) {
        final Object key = keys[i];
        logger.info("Group: '" + key + "' Size: " + expressionsByGroup.getValueCount(key));
        final Object[] objects = expressionsByGroup.toArray(key);
        for (int j = 0; j < objects.length; j++) {
            ExpressionMetaData metaData = (ExpressionMetaData) objects[j];
            logger.info("   " + metaData.getExpressionType());

        }
    }
}

From source file:Main.java

public static <T> T loadBean(Node node, Class<T> beanClass)
        throws IntrospectionException, InstantiationException, IllegalAccessException, IllegalArgumentException,
        DOMException, InvocationTargetException {
    T store = beanClass.newInstance();/*w ww.  j  a  v a 2s.  com*/

    Map<String, PropertyDescriptor> properties = new HashMap<String, PropertyDescriptor>();
    BeanInfo beanInfo = Introspector.getBeanInfo(beanClass);
    for (PropertyDescriptor property : beanInfo.getPropertyDescriptors()) {
        properties.put(property.getName(), property);
    }

    NamedNodeMap attributes = node.getAttributes();
    for (int i = 0; i < attributes.getLength(); i++) {
        Node attribute = attributes.item(i);
        PropertyDescriptor property = properties.get(attribute.getNodeName());
        if (property != null && property.getPropertyType().equals(String.class)
                && property.getWriteMethod() != null) {
            property.getWriteMethod().invoke(store, attribute.getNodeValue());
        }
    }

    NodeList childNodes = node.getChildNodes();
    for (int i = 0; i < childNodes.getLength(); i++) {
        Node child = childNodes.item(i);
        PropertyDescriptor property = properties.get(child.getNodeName());
        if (property != null && property.getPropertyType().equals(String.class)
                && property.getWriteMethod() != null) {
            property.getWriteMethod().invoke(store, child.getTextContent());
        }
    }

    return store;
}

From source file:Main.java

public static void makeTransient(Class<?> beanClass, String... pdNames) {
    try {/* w w  w . ja  v a 2 s . co m*/
        BeanInfo info = Introspector.getBeanInfo(beanClass);
        PropertyDescriptor[] descs = info.getPropertyDescriptors();
        if (descs == null) {
            throw new RuntimeException("Cannot access property descriptor for class " + beanClass);
        }
        Map<String, PropertyDescriptor> mapping = new HashMap<String, PropertyDescriptor>();
        for (PropertyDescriptor desc : descs) {
            mapping.put(desc.getName(), desc);
        }
        for (String pdName : pdNames) {
            PropertyDescriptor desc = mapping.get(pdName);
            if (desc == null) {
                throw new RuntimeException("Property " + pdName + " does not exist in " + beanClass);
            }
            desc.setValue("transient", Boolean.TRUE);
        }
    } catch (IntrospectionException ie) {
        throw new RuntimeException(ie);
    }
}

From source file:PropertyUtils.java

/**
 * Get map with property descriptors for the specified bean class
 *//*from  ww  w.ja  v  a  2s  .  c  o m*/
private static Map getPropertyDescriptors(Class clazz) {
    HashMap map = (HashMap) descriptorCache.get(clazz);
    if (map == null) {
        BeanInfo beanInfo = null;
        try {
            beanInfo = Introspector.getBeanInfo(clazz);
        } catch (IntrospectionException e) {
            return Collections.EMPTY_MAP;
        }
        PropertyDescriptor[] descriptors = beanInfo.getPropertyDescriptors();
        if (descriptors == null)
            descriptors = new PropertyDescriptor[0];
        map = new HashMap(descriptors.length);
        for (int i = 0; i < descriptors.length; i++)
            map.put(descriptors[i].getName(), descriptors[i]);
        descriptorCache.put(clazz, map);
    }
    return map;
}

From source file:BeanUtility.java

/** This method takes a JavaBean and generates a standard toString() type result for it.
 * @param o JavaBean object to stringinate
 * @return STRINGIATION! Stringingating the countryside. Stringinating all the peasants.
 *//*w  w w.j  a  va 2s . c  o  m*/
public static String beanToString(Object o) {
    StringBuffer result = new StringBuffer();
    if (o == null)
        return "--- null";
    result.append("--- begin");
    result.append(o.getClass().getName());
    result.append(" hash: ");
    result.append(o.hashCode());
    result.append("\r\n");
    try {
        PropertyDescriptor[] pds = Introspector.getBeanInfo(o.getClass()).getPropertyDescriptors();
        for (int pdi = 0; pdi < pds.length; pdi++) {
            try {
                result.append(
                        "Property: " + pds[pdi].getName() + " Value: " + pds[pdi].getReadMethod().invoke(o));
            } catch (IllegalAccessException iae) {
                result.append("Property: " + pds[pdi].getName() + " (Illegal Access to Value) ");
            } catch (InvocationTargetException iae) {
                result.append(
                        "Property: " + pds[pdi].getName() + " (InvocationTargetException) " + iae.toString());
            } catch (Exception e) {
                result.append("Property: " + pds[pdi].getName() + " (Other Exception )" + e.toString());
            }
            result.append("\r\n");
        }

    } catch (IntrospectionException ie) {
        result.append("Introspection Exception: " + ie.toString());
        result.append("\r\n");
    }
    result.append("--- end ");
    result.append(o.getClass().getName());
    result.append(" hash: ");
    result.append(o.hashCode());
    result.append("\n");
    return result.toString();
}

From source file:org.bibsonomy.util.ObjectUtils.java

/**
 * copies all property values (all properties that have a getter and setter) from the source to the target
 * //from  w  w  w.  j  a v a  2s  . c  o m
 * @param <T> 
 * @param source the source object
 * @param target the target object
 */
public static <T> void copyPropertyValues(final T source, final T target) {
    try {
        final BeanInfo biSource = Introspector.getBeanInfo(source.getClass());
        final BeanInfo biTarget = Introspector.getBeanInfo(target.getClass());

        /* 
         * source can be a subtype of target
         * to ensure that a setter of the subtype isn't called choose the array
         * that contains less properties
         */
        final PropertyDescriptor[] sourceProperties = biSource.getPropertyDescriptors();
        final PropertyDescriptor[] targetProperties = biTarget.getPropertyDescriptors();
        final PropertyDescriptor[] copyProperties = sourceProperties.length > targetProperties.length
                ? targetProperties
                : sourceProperties;

        /*
         * loop through all properties
         */
        for (final PropertyDescriptor d : copyProperties) {
            final Method getter = d.getReadMethod();
            final Method setter = d.getWriteMethod();

            if (present(getter) && present(setter)) {
                // get the value from the source
                final Object value = getter.invoke(source, (Object[]) null);
                // and set in in the target
                setter.invoke(target, value);
            }
        }
    } catch (Exception ex) {
        log.error("error while copying property values from an object " + source.getClass() + " to an object "
                + target.getClass(), ex);
    }
}