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.myfaces.tomahawk.util.ErrorPageWriter.java

private static void writeAttributes(Writer writer, UIComponent c) {
    try {/*www  .  j  a  v a2s  . co m*/
        BeanInfo info = Introspector.getBeanInfo(c.getClass());
        PropertyDescriptor[] pd = info.getPropertyDescriptors();
        Method m = null;
        Object v = null;
        String str = null;
        for (int i = 0; i < pd.length; i++) {
            if (pd[i].getWriteMethod() != null && Arrays.binarySearch(IGNORE, pd[i].getName()) < 0) {
                m = pd[i].getReadMethod();
                try {
                    v = m.invoke(c, null);
                    if (v != null) {
                        if (v instanceof Collection || v instanceof Map || v instanceof Iterator) {
                            continue;
                        }
                        writer.write(" ");
                        writer.write(pd[i].getName());
                        writer.write("=\"");
                        if (v instanceof Expression) {
                            str = ((Expression) v).getExpressionString();
                        }
                        writer.write(str.replaceAll("<", TS));
                        writer.write("\"");
                    }
                } catch (Exception e) {
                    // do nothing
                }
            }
        }

        ValueExpression binding = c.getValueExpression("binding");
        if (binding != null) {
            writer.write(" binding=\"");
            writer.write(binding.getExpressionString().replaceAll("<", TS));
            writer.write("\"");
        }
    } catch (Exception e) {
        // do nothing
    }
}

From source file:org.eclipse.wb.internal.swing.databinding.model.beans.BeanSupport.java

/**
 * @return {@link Image} represented given bean class.
 *//*from  www .ja va  2  s. c o  m*/
public Image getBeanImage(Class<?> beanClass, JavaInfo javaInfo, boolean useDefault) throws Exception {
    // check java info
    if (javaInfo != null) {
        return null;
    }
    // prepare cached image
    Image beanImage = m_classToImage.get(beanClass);
    // check load image
    if (beanImage == null) {
        try {
            // load AWT image
            BeanInfo beanInfo = Introspector.getBeanInfo(beanClass);
            java.awt.Image awtBeanIcon = beanInfo.getIcon(BeanInfo.ICON_COLOR_16x16);
            if (awtBeanIcon == null) {
                // set default
                beanImage = useDefault ? Activator.getImage("javabean.gif") : null;
            } else {
                // convert to SWT image
                // FIXME: memory leak
                beanImage = SwingImageUtils.convertImage_AWT_to_SWT(awtBeanIcon);
            }
        } catch (Throwable e) {
            // set default
            beanImage = useDefault ? Activator.getImage("javabean.gif") : null;
        }
        m_classToImage.put(beanClass, beanImage);
    }
    return beanImage;
}

From source file:org.apache.struts2.interceptor.debugging.DebuggingInterceptor.java

/**
 * Recursive function to serialize objects to XML. Currently it will
 * serialize Collections, maps, Arrays, and JavaBeans. It maintains a stack
 * of objects serialized already in the current functioncall. This is used
 * to avoid looping (stack overflow) of circular linked objects. Struts and
 * XWork objects are ignored.//  ww  w.j av a2 s  .  com
 *
 * @param bean   The object you want serialized.
 * @param name   The name of the object, used for element &lt;name/&gt;
 * @param writer The XML writer
 * @param stack  List of objects we're serializing since the first calling
 *               of this function (to prevent looping on circular references).
 */
protected void serializeIt(Object bean, String name, PrettyPrintWriter writer, List<Object> stack) {
    writer.flush();
    // Check stack for this object
    if ((bean != null) && (stack.contains(bean))) {
        if (log.isInfoEnabled()) {
            log.info("Circular reference detected, not serializing object: " + name);
        }
        return;
    } else if (bean != null) {
        // Push object onto stack.
        // Don't push null objects ( handled below)
        stack.add(bean);
    }
    if (bean == null) {
        return;
    }
    String clsName = bean.getClass().getName();

    writer.startNode(name);

    // It depends on the object and it's value what todo next:
    if (bean instanceof Collection) {
        Collection col = (Collection) bean;

        // Iterate through components, and call ourselves to process
        // elements
        for (Object aCol : col) {
            serializeIt(aCol, "value", writer, stack);
        }
    } else if (bean instanceof Map) {

        Map map = (Map) bean;

        // Loop through keys and call ourselves
        for (Object key : map.keySet()) {
            Object Objvalue = map.get(key);
            serializeIt(Objvalue, key.toString(), writer, stack);
        }
    } else if (bean.getClass().isArray()) {
        // It's an array, loop through it and keep calling ourselves
        for (int i = 0; i < Array.getLength(bean); i++) {
            serializeIt(Array.get(bean, i), "arrayitem", writer, stack);
        }
    } else {
        if (clsName.startsWith("java.lang")) {
            writer.setValue(bean.toString());
        } else {
            // Not java.lang, so we can call ourselves with this object's
            // values
            try {
                BeanInfo info = Introspector.getBeanInfo(bean.getClass());
                PropertyDescriptor[] props = info.getPropertyDescriptors();

                for (PropertyDescriptor prop : props) {
                    String n = prop.getName();
                    Method m = prop.getReadMethod();

                    // Call ourselves with the result of the method
                    // invocation
                    if (m != null) {
                        serializeIt(m.invoke(bean), n, writer, stack);
                    }
                }
            } catch (Exception e) {
                log.error(e, e);
            }
        }
    }

    writer.endNode();

    // Remove object from stack
    stack.remove(bean);
}

From source file:storybook.model.EntityUtil.java

public static void printBeanProperties(AbstractEntity entity) {
    SbApp.trace("EntityUtil.printBeanProperties(" + entity.getClass().getName() + ")");
    try {//  w w w.  j  av  a 2 s. c o m
        BeanInfo bi = Introspector.getBeanInfo(entity.getClass());
        for (PropertyDescriptor propDescr : bi.getPropertyDescriptors()) {
            String name = propDescr.getName();
            Object val = propDescr.getReadMethod().invoke(entity);
            String isNull = "not null";
            if (val == null) {
                isNull = "is null";
            }
            System.out.println("EntityUtil.printProperties(): " + name + ": '" + val + "' "
                    + (val == null ? "isNull" : "not null"));
        }
    } catch (IntrospectionException | IllegalAccessException | IllegalArgumentException
            | InvocationTargetException e) {
        System.err.println("EntityUtil.printBeanProperties(" + entity + ") Exception : " + e.getMessage());
    }
}

From source file:es.logongas.ix3.util.ReflectionUtil.java

/**
 * Este mtodo/* ww w .j a va 2 s. co m*/
 *
 * @param clazz
 * @param propertyName El nombre de la propiedad permite que sean varias
 * "nested" con puntos. Ej: "prop1.prop2.prop3"
 * @return
 */
private static PropertyDescriptor getPropertyDescriptor(Class clazz, String propertyName) {
    try {
        BeanInfo beanInfo = Introspector.getBeanInfo(clazz);

        PropertyDescriptor[] propertyDescriptors = beanInfo.getPropertyDescriptors();
        if ((propertyName == null) || (propertyName.trim().isEmpty())) {
            throw new RuntimeException("El parametro propertyName no puede ser null o estar vacio");
        }

        String leftPropertyName; //El nombre de la propiedad antes del primer punto
        String rigthPropertyName; //El nombre de la propiedad despues del primer punto

        int indexPoint = propertyName.indexOf(".");
        if (indexPoint < 0) {
            leftPropertyName = propertyName;
            rigthPropertyName = null;
        } else if ((indexPoint > 0) && (indexPoint < (propertyName.length() - 1))) {
            leftPropertyName = propertyName.substring(0, indexPoint);
            rigthPropertyName = propertyName.substring(indexPoint + 1);
        } else {
            throw new RuntimeException("El punto no puede estar ni al principio ni al final");
        }

        PropertyDescriptor propertyDescriptorFind = null;
        for (PropertyDescriptor propertyDescriptor : propertyDescriptors) {
            if (propertyDescriptor.getName().equals(leftPropertyName)) {
                propertyDescriptorFind = propertyDescriptor;
                break;
            }
        }

        if (propertyDescriptorFind == null) {
            throw new RuntimeException("No existe el propertyDescriptorFind de " + leftPropertyName);
        }

        if (rigthPropertyName != null) {
            Method readMethod = propertyDescriptorFind.getReadMethod();
            if (readMethod == null) {
                throw new RuntimeException("No existe el metodo 'get' de " + leftPropertyName);
            }

            Class readClass = readMethod.getReturnType();
            return getPropertyDescriptor(readClass, rigthPropertyName);
        } else {
            return propertyDescriptorFind;
        }

    } catch (Exception ex) {
        throw new RuntimeException(ex);
    }
}

From source file:de.jwic.base.Control.java

/**
 * Builds Json object string of all methods marked with 
 * IncludeJsOption Annotation./* w w w .j  a v  a  2 s . co  m*/
 * If Enums are used getCode needs to be implemented, which returns the value
 * @return
 */
public String buildJsonOptions() {
    try {
        StringWriter sw = new StringWriter();
        JSONWriter writer = new JSONWriter(sw);
        writer.object();
        BeanInfo beanInfo;
        beanInfo = Introspector.getBeanInfo(getClass());

        PropertyDescriptor[] pds = beanInfo.getPropertyDescriptors();

        for (PropertyDescriptor pd : pds) {
            Method getter = pd.getReadMethod();
            if (getter != null && pd.getReadMethod().getAnnotation(IncludeJsOption.class) != null) {
                Object o = getter.invoke(this);
                if (o != null) {
                    if (o instanceof Enum) {
                        Method m = o.getClass().getMethod("getCode", null);
                        if (m != null) {
                            writer.key(pd.getDisplayName()).value(m.invoke(o));
                            continue;
                        }
                    } else if (o instanceof Date) {
                        writer.key(pd.getDisplayName())
                                .value(new JsDateString((Date) o, getSessionContext().getTimeZone()));
                        continue;
                    }

                    // if name has been changed use that one.
                    IncludeJsOption annotation = pd.getReadMethod().getAnnotation(IncludeJsOption.class);
                    if (annotation.jsPropertyName() != null && annotation.jsPropertyName().length() > 0) {
                        writer.key(annotation.jsPropertyName());
                    } else {
                        writer.key(pd.getDisplayName());
                    }
                    writer.value(o);
                }
            }
        }
        writer.endObject();
        return sw.toString();
    } catch (Exception e) {
        throw new RuntimeException("Error while configuring Json Option for " + this.getClass().getName());
    }
}

From source file:com.icsshs.datatransfer.database.impl.QueryBeanProcessor.java

/**
 * Returns a PropertyDescriptor[] for the given Class.
 *
 * @param c The Class to retrieve PropertyDescriptors for.
 * @return A PropertyDescriptor[] describing the Class.
 * @throws SQLException if introspection failed.
 *///  w  ww .java 2  s .  c o  m
private PropertyDescriptor[] propertyDescriptors(Class<?> c) throws SQLException {
    // Introspector caches BeanInfo classes for better performance
    BeanInfo beanInfo = null;
    try {
        beanInfo = Introspector.getBeanInfo(c);

    } catch (IntrospectionException e) {
        throw new SQLException("Bean introspection failed: " + e.getMessage());
    }

    return beanInfo.getPropertyDescriptors();
}

From source file:com.kangdainfo.common.util.BeanUtil.java

/**
 * This method takes 2 JavaBeans of the same type and copies the properties of one bean to the other.
 * <br>/*from ww w .  j  av  a  2s .  co m*/
 * @param from
 * @param to
 * @param ignoreFields
 * @throws InvocationTargetException
 * @throws IntrospectionException
 */
public static void copyBeanToBean(Object from, Object to, String[] ignoreFields)
        throws InvocationTargetException, IntrospectionException {
    if (from != null && to != null) {
        PropertyDescriptor[] pds = Introspector.getBeanInfo(from.getClass()).getPropertyDescriptors();
        for (int i = 0; i < pds.length; i++) {
            try {
                boolean flag = false;
                if (ignoreFields != null && ignoreFields.length > 0) {
                    for (int j = 0; j < ignoreFields.length; j++) {
                        if (pds[i].getName().equals(ignoreFields[j]))
                            flag = true;
                    }
                }
                if (pds[i].getName().equals("class") || flag == true)
                    continue;
                Object[] value = { pds[i].getReadMethod().invoke(from) };
                if (pds[i].getWriteMethod() != null)
                    pds[i].getWriteMethod().invoke(to, value);
            } catch (IllegalAccessException iae) {
                iae.printStackTrace();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
}

From source file:com.netspective.medigy.model.data.EntitySeedDataPopulator.java

protected void populateEntity(final Session session, final Class entityClass, final String[] propertyList,
        final Object[][] data) throws HibernateException {
    try {/*from   w w  w . j  a va  2s  . c  om*/
        final Hashtable pdsByName = new Hashtable();
        final BeanInfo beanInfo = Introspector.getBeanInfo(entityClass);
        final PropertyDescriptor[] descriptors = beanInfo.getPropertyDescriptors();
        for (int i = 0; i < descriptors.length; i++) {
            final PropertyDescriptor descriptor = descriptors[i];
            if (descriptor.getWriteMethod() != null)
                pdsByName.put(descriptor.getName(), descriptor.getWriteMethod());
        }

        for (int i = 0; i < data.length; i++) {
            final Object entityObject = entityClass.newInstance();
            for (int j = 0; j < propertyList.length; j++) {
                final Method setter = (Method) pdsByName.get(propertyList[j]);
                if (setter != null)
                    setter.invoke(entityObject, new Object[] { data[i][j] });
            }
            session.save(entityObject);
        }
    } catch (Exception e) {
        log.error(e);
        throw new HibernateException(e);
    }
}

From source file:net.sf.jrf.domain.PersistentObjectDynaClass.java

/** Factory method to create a <code>PersistentObjectDynaClass</code> based on bean properties
 * of the <code>PersistentObject</code> managed by the <code>AbstractDomain</code> instance parameter.
 * If the object is a composite, <code>Map</code> and <code>List</code> properties will
 * be included.//  w  ww  .j a va2s.co  m
 * @param domain <code>AbstractDomain</code> instance to inspect.
 * @param beanClass class name of the implementer of <code>DynaBean</code>
 *  returned <code>PersistentObjectDynaClass</code>'s <code>PersistentObjectDynaProperty</code> list.
 * @return <code>PersistentObjectDynaClass</code> based on internal column specifications.
 */
static public PersistentObjectDynaClass createPersistentObjectDynaClass(AbstractDomain domain,
        Class beanClass) {
    BeanInfo beanInfo;
    PersistentObject obj = domain.newPersistentObject();
    // Introspect the Persistent Object.
    try {
        beanInfo = Introspector.getBeanInfo(obj.getClass());
    } catch (IntrospectionException ex) {
        throw new ConfigurationException(ex, "Unexpected introspection exception on " + obj.getClass());
    }
    PropertyDescriptor[] properties = beanInfo.getPropertyDescriptors();
    HashMap propertyMap = new HashMap();
    for (int i = 0; i < properties.length; i++) {
        if (properties[i].getReadMethod() != null) {
            Class returnType = properties[i].getReadMethod().getReturnType();
            /** NO - include them
             (Ignore Maps and Lists from composites)
            if (java.util.Map.class.isAssignableFrom(returnType) ||
                java.util.List.class.isAssignableFrom(returnType))
                continue;
            **/
            String writeMethodName = properties[i].getWriteMethod() == null ? null
                    : properties[i].getWriteMethod().getName();

            propertyMap.put(properties[i].getName(), new PersistentObjectDynaProperty(properties[i].getName(),
                    returnType, properties[i].getReadMethod().getName(), writeMethodName));
        }
    }
    // Reconcile bean properties with the column specifications.
    Iterator columnSpecs = domain.getColumnSpecs().iterator();
    while (columnSpecs.hasNext()) {
        ColumnSpec c = (ColumnSpec) columnSpecs.next();
        if (c instanceof CompoundPrimaryKeyColumnSpec) {
            CompoundPrimaryKeyColumnSpec cp = (CompoundPrimaryKeyColumnSpec) c;
            Iterator iter = cp.getColumnSpecs().iterator();
            while (iter.hasNext()) {
                PersistentObjectDynaProperty p = updatePropertyMap((ColumnSpec) iter.next(), propertyMap);
                // Force dyna property for primary key to true.  Value for compound keys does not
                // have this value set automatically.
                p.setPrimaryKey(true);
            }
        } else {
            updatePropertyMap(c, propertyMap);
        }
    }
    List list = new ArrayList(propertyMap.values());
    return new PersistentObjectDynaClass(domain.getPropertyName(), beanClass, obj.getClass(), list);
}