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.rhq.plugins.platform.PlatformComponent.java

private Object getObjectProperty(Object object, String name) {
    try {/*from  w w w .  j ava2 s.  c om*/
        BeanInfo info = Introspector.getBeanInfo(object.getClass());
        for (PropertyDescriptor pd : info.getPropertyDescriptors()) {
            if (pd.getName().equals(name)) {
                return pd.getReadMethod().invoke(object);
            }
        }
    } catch (Exception skip) {
        if (log.isDebugEnabled())
            log.debug(skip);
    }

    return Double.NaN;
}

From source file:de.xwic.appkit.core.transport.xml.XmlBeanSerializer.java

/**
 * @param doc//from   w  w  w .  j a va2  s  .  c o m
 * @param string
 * @param query
 * @throws IntrospectionException
 * @throws InvocationTargetException
 * @throws IllegalAccessException
 * @throws IllegalArgumentException
 */
public void serializeBean(Element elm, String elementName, Object bean) throws TransportException {

    Element root = elm.addElement(elementName);

    root.addAttribute("type", bean.getClass().getName());

    try {
        BeanInfo beanInfo = Introspector.getBeanInfo(bean.getClass());
        for (PropertyDescriptor pd : beanInfo.getPropertyDescriptors()) {

            if (!"class".equals(pd.getName())) {
                Element pElm = root.addElement(pd.getName());
                Method mRead = pd.getReadMethod();
                if (mRead == null) {
                    log.debug(String.format("No '%s' property on '%s'.", pd.getName(), bean.getClass()));
                    continue;
                }
                Object value = mRead.invoke(bean, NO_ARGS);

                boolean addType = true;
                addType = value != null && !value.getClass().equals(pd.getPropertyType())
                        && !pd.getPropertyType().isPrimitive();
                addValue(pElm, value, addType);
            }

        }
    } catch (Exception e) {
        throw new TransportException("Error serializing bean: " + e, e);
    }

}

From source file:org.rhq.plugins.platform.ProcessComponent.java

private Object lookupAttributeProperty(Object value, String property) {
    String[] ps = property.split("\\.", 2);

    String searchProperty = ps[0];

    // Try to use reflection
    try {/*w  w w .  ja  v  a 2  s. c  om*/
        PropertyDescriptor[] pds = Introspector.getBeanInfo(value.getClass()).getPropertyDescriptors();
        for (PropertyDescriptor pd : pds) {
            if (pd.getName().equals(searchProperty)) {
                value = pd.getReadMethod().invoke(value);
                break;
            }
        }
    } catch (Exception e) {
        if (log.isDebugEnabled()) {
            log.debug("Unable to read property [" + property + "]; measurement attribute [" + searchProperty
                    + "] not found on [" + this.resourceContext.getResourceKey() + "]. Cause: " + e);
        }
    }

    if (ps.length > 1) {
        value = lookupAttributeProperty(value, ps[1]);
    }

    return value;
}

From source file:com.wavemaker.runtime.data.util.QueryHandler.java

private Object cloneObject(Object oldObj, Object newObj, Class cls) {
    PropertyDescriptor[] beanProps;
    try {// w  w w.  j a va 2  s . com
        beanProps = Introspector.getBeanInfo(cls).getPropertyDescriptors();
        for (PropertyDescriptor propertyDescriptor : beanProps) {
            if (propertyDescriptor.getName().equals("class")) {
                continue;
            }
            Method getter = propertyDescriptor.getReadMethod();
            Method setter = propertyDescriptor.getWriteMethod();
            Object val = getter.invoke(oldObj);
            setter.invoke(newObj, val);
        }
    } catch (Exception ex) {
        throw new WMRuntimeException(ex);
    }

    return newObj;
}

From source file:name.livitski.tools.persista.AbstractDAO.java

protected Map<String, PropertyDescriptor> introspectProperties() {
    if (null == entityProps)
        try {/* w w  w.  ja v a 2 s  . co  m*/
            final BeanInfo beanInfo = Introspector.getBeanInfo(entityClass);
            final PropertyDescriptor[] propertyDescriptors = beanInfo.getPropertyDescriptors();
            entityProps = new HashMap<String, PropertyDescriptor>(propertyDescriptors.length, 1f);
            for (final PropertyDescriptor pd : propertyDescriptors) {
                entityProps.put(pd.getName(), pd);
            }
        } catch (IntrospectionException e) {
            throw new UnsupportedOperationException("Introspection failed for entity " + entityClass, e);
        }
    return entityProps;
}

From source file:org.seasar.karrta.jcr.session.JcrSessionFactory.java

/**
 * add event listeners.//  w w  w  .  ja  v a 2s . c om
 * 
 * @param session
 * @return
 * @throws JcrRepositoryRuntimeException
 */
protected void addEventListeners(Session session) throws JcrRepositoryRuntimeException {
    if (this.eventListeners == null || this.eventListeners.size() == 0) {
        return;
    }
    try {
        Workspace workspace = session.getWorkspace();
        EventListenerDefinition eventDefinition = null;

        for (Iterator<?> i = this.eventListeners.iterator(); i.hasNext();) {
            Object bean = i.next();
            eventDefinition = new EventListenerDefinition();

            BeanInfo beanInfo = Introspector.getBeanInfo(bean.getClass());
            for (PropertyDescriptor property : beanInfo.getPropertyDescriptors()) {
                Method getter = property.getReadMethod();

                if (getter == null)
                    continue;
                eventDefinition.setProperty(getter.getName(), getter.invoke(bean, null));
            }
            workspace.getObservationManager().addEventListener(eventDefinition.getListener(),
                    eventDefinition.getEventTypes(), eventDefinition.getAbsPath(), eventDefinition.isDeep(),
                    eventDefinition.getUuids(), eventDefinition.getNodeTypeNames(),
                    eventDefinition.getNoLocal());
        }

    } catch (IllegalAccessException e) {
        throw new JcrRepositoryRuntimeException("", e);
    } catch (IntrospectionException e) {
        throw new JcrRepositoryRuntimeException("", e);
    } catch (InvocationTargetException e) {
        throw new JcrRepositoryRuntimeException("", e);
    } catch (RepositoryException e) {
        throw new JcrRepositoryRuntimeException("", e);
    }
}

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

public static String[] getPropertyNames(Object o) throws IntrospectionException {
    PropertyDescriptor[] pds = Introspector.getBeanInfo(o.getClass()).getPropertyDescriptors();
    String[] propertyNames = new String[pds.length];

    for (int i = 0; i < pds.length; i++) {
        propertyNames[i] = pds[i].getName();
    }/*from www.  ja  v  a2 s. c o m*/

    return propertyNames;
}

From source file:org.eclipse.amp.amf.parameters.AParInterpreter.java

public void assignValues(Object[] assignees, MultiStatus status) {
    Map<PropertyDescriptor, Object> assigneeForProperty = new HashMap<PropertyDescriptor, Object>();
    Map<String, PropertyDescriptor> propertyForID = new HashMap<String, PropertyDescriptor>();
    for (Object assignee : assignees) {
        PropertyDescriptor[] infoProperties;
        try {// w  w  w.ja  v a  2  s. c o m
            infoProperties = Introspector.getBeanInfo(assignee.getClass()).getPropertyDescriptors();
            for (PropertyDescriptor propertyDescriptor : infoProperties) {
                propertyForID.put(StringUtils.capitalize(propertyDescriptor.getName()), propertyDescriptor);
                assigneeForProperty.put(propertyDescriptor, assignee);
            }
        } catch (IntrospectionException e) {
            warn(status, "Could not introspect on \"" + assignee + ". Continuing.", e);
        }
    }
    for (Parameter param : getParameters()) {
        if (param instanceof SingleParameter) {
            SingleParameter sp = (SingleParameter) param;
            SAttribute attribute = sp.getAttribute();
            try {
                try {
                    String attrName = StringUtils.capitalize(attribute.getID());
                    PropertyDescriptor desc = propertyForID.get(attrName);
                    if (desc == null && attribute.getOwner() != getRootContext()) {
                        // We need to qualify name
                        attrName = StringUtils.capitalize(attribute.getOwner().getID()) + attrName;
                        desc = propertyForID.get(attrName);
                    }
                    if (desc == null) {
                        warn(status, "Could not find attribute \"" + attrName + "\" in " + assignees, null);
                    } else {
                        Object assignee = assigneeForProperty.get(desc);
                        if (attribute.getSType() == SAttributeType.REAL_LITERAL) {
                            assign(desc, assignee, Double.valueOf(AParInterpreter.value(sp.getValue())));
                        } else if (attribute.getSType() == SAttributeType.INTEGER_LITERAL) {
                            assign(desc, assignee, Integer.valueOf(AParInterpreter.value(sp.getValue())));
                        } else if (attribute.getSType() == SAttributeType.BOOLEAN_LITERAL) {
                            assign(desc, assignee, (((BooleanValue) sp.getValue()).getValue() == BOOLEAN.TRUE));
                        } else if (attribute.getSType() == SAttributeType.SYMBOL_LITERAL) {
                            String string = AParInterpreter.value(sp.getValue());
                            string = StringUtils.replace(string, "|", getLocalPath() + "/");
                            assign(desc, assignee, string);
                        } else {
                            status.add(new Status(Status.WARNING, "org.eclipse.amp.amf.testing.ide",
                                    "Unrecognized type: " + attribute.getSType()));
                        }
                    }
                } catch (Exception e) {
                    status.add(new Status(Status.WARNING, "org.eclipse.amp.amf.testing.ide",
                            "Problem assigning parameter: " + attribute, e));
                    continue;
                }
            } catch (Exception e) {
                status.add(new Status(Status.WARNING, "org.eclipse.amp.amf.testing.ide",
                        "Couldn't obtain property descriptors for \"" + getModelClass() + "\"", e));
            }
        }
    }
}

From source file:com.artistech.protobuf.TuioProtoConverter.java

@Override
public Object convertFromProtobuf(final GeneratedMessage obj) {
    Object target;//from   ww w  .  j av a2s .  co m

    if (TuioProtos.Blob.class.isAssignableFrom(obj.getClass())) {
        target = new TUIO.TuioBlob();
    } else if (TuioProtos.Time.class.isAssignableFrom(obj.getClass())) {
        target = new TUIO.TuioTime();
    } else if (TuioProtos.Cursor.class.isAssignableFrom(obj.getClass())) {
        target = new TUIO.TuioCursor();
    } else if (TuioProtos.Object.class.isAssignableFrom(obj.getClass())) {
        target = new TUIO.TuioObject();
    } else if (TuioProtos.Point.class.isAssignableFrom(obj.getClass())) {
        target = new TUIO.TuioPoint();
    } else {
        return null;
    }

    try {
        PropertyDescriptor[] targetProps = Introspector.getBeanInfo(target.getClass()).getPropertyDescriptors();

        BeanInfo beanInfo = Introspector.getBeanInfo(obj.getClass());
        PropertyDescriptor[] messageProps = beanInfo.getPropertyDescriptors();
        Method[] methods = obj.getClass().getMethods();

        for (PropertyDescriptor targetProp : targetProps) {
            for (PropertyDescriptor messageProp : messageProps) {
                if (targetProp.getName().equals(messageProp.getName())) {
                    Method writeMethod = targetProp.getWriteMethod();
                    Method readMethod = null;
                    for (Method m : methods) {
                        if (writeMethod != null
                                && m.getName().equals(writeMethod.getName().replaceFirst("set", "get"))) {
                            readMethod = m;
                            break;
                        }
                    }
                    try {
                        if (writeMethod != null && readMethod != null && targetProp.getReadMethod() != null) {
                            boolean primitiveOrWrapper = ClassUtils
                                    .isPrimitiveOrWrapper(targetProp.getReadMethod().getReturnType());

                            if (readMethod.getParameterTypes().length > 0) {
                                if (DeepCopy) {
                                    if (!Modifier.isAbstract(targetProp.getPropertyType().getModifiers())) {
                                        //basically, ArrayList
                                        Object newInstance = targetProp.getPropertyType().newInstance();
                                        Method addMethod = newInstance.getClass().getMethod("add",
                                                Object.class);
                                        Method m = obj.getClass().getMethod(readMethod.getName() + "Count");
                                        int size = (int) m.invoke(obj);
                                        for (int ii = 0; ii < size; ii++) {
                                            Object o = readMethod.invoke(obj, ii);
                                            addMethod.invoke(newInstance, o);
                                        }
                                        writeMethod.invoke(target, newInstance);
                                    } else if (Collection.class
                                            .isAssignableFrom(targetProp.getPropertyType())) {
                                        //do something if it is a collection or iterable...
                                    }
                                }
                            } else if (primitiveOrWrapper) {
                                writeMethod.invoke(target, messageProp.getReadMethod().invoke(obj));
                            } else {
                                if (GeneratedMessage.class
                                        .isAssignableFrom(messageProp.getReadMethod().getReturnType())) {

                                    GeneratedMessage invoke = (GeneratedMessage) messageProp.getReadMethod()
                                            .invoke(obj);
                                    Object val = null;
                                    for (ProtoConverter converter : services) {
                                        if (converter.supportsConversion(invoke)) {
                                            val = convertFromProtobuf(invoke);
                                            break;
                                        }
                                    }
                                    if (val != null) {
                                        writeMethod.invoke(target, val);
                                    }
                                }
                                //                                    System.out.println("Prop1 Name!: " + targetProp.getName());
                            }
                        }
                    } catch (NullPointerException ex) {
                        //Logger.getLogger(ZeroMqMouse.class.getName()).log(Level.SEVERE, null, ex);
                    } catch (InstantiationException | NoSuchMethodException | IllegalArgumentException
                            | SecurityException | IllegalAccessException | InvocationTargetException ex) {
                        logger.error(ex);
                    }
                    break;
                }
            }
        }
    } catch (java.beans.IntrospectionException ex) {
        logger.fatal(ex);
    }
    return target;
}

From source file:com.sun.faces.el.impl.BeanInfoManager.java

/**
 * Initializes by mapping property names to BeanInfoProperties
 *//*from   www . j  a v  a 2s. c  o  m*/
void initialize() throws ElException {
    try {
        mBeanInfo = Introspector.getBeanInfo(mBeanClass);

        mPropertyByName = new HashMap();
        mIndexedPropertyByName = new HashMap();
        PropertyDescriptor[] pds = mBeanInfo.getPropertyDescriptors();
        for (int i = 0; pds != null && i < pds.length; i++) {
            // Treat as both an indexed property and a normal property
            PropertyDescriptor pd = pds[i];
            if (pd instanceof IndexedPropertyDescriptor) {
                IndexedPropertyDescriptor ipd = (IndexedPropertyDescriptor) pd;
                Method readMethod = getPublicMethod(ipd.getIndexedReadMethod());
                Method writeMethod = getPublicMethod(ipd.getIndexedWriteMethod());
                BeanInfoIndexedProperty property = new BeanInfoIndexedProperty(readMethod, writeMethod, ipd);

                mIndexedPropertyByName.put(ipd.getName(), property);
            }

            Method readMethod = getPublicMethod(pd.getReadMethod());
            Method writeMethod = getPublicMethod(pd.getWriteMethod());
            BeanInfoProperty property = new BeanInfoProperty(readMethod, writeMethod, pd);

            mPropertyByName.put(pd.getName(), property);
        }

        mEventSetByName = new HashMap();
        EventSetDescriptor[] esds = mBeanInfo.getEventSetDescriptors();
        for (int i = 0; esds != null && i < esds.length; i++) {
            EventSetDescriptor esd = esds[i];
            mEventSetByName.put(esd.getName(), esd);
        }
    } catch (IntrospectionException exc) {
        if (log.isWarnEnabled()) {
            log.warn(MessageUtil.getMessageWithArgs(Constants.EXCEPTION_GETTING_BEANINFO, mBeanClass.getName()),
                    exc);
        }
    }
}