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:BeanUtility.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  w ww  . j a v  a 2  s .  c  o  m*/
    return propertyNames;
}

From source file:jp.primecloud.auto.util.StringUtils.java

public static String reflectToString(Object object) {
    if (object == null) {
        return null;
    }/*from   w w  w  . jav a  2 s  .com*/

    // String??
    if (object instanceof String) {
        return (String) object;
    }

    // ??
    if (object instanceof Number) {
        return object.toString();
    }

    // Boolean??
    if (object instanceof Boolean) {
        return object.toString();
    }

    // Character??
    if (object instanceof Character) {
        return object.toString();
    }

    // ???
    if (object instanceof Object[]) {
        return reflectToString(Arrays.asList((Object[]) object));
    }

    // ??
    if (object instanceof Collection<?>) {
        Iterator<?> iterator = ((Collection<?>) object).iterator();
        if (!iterator.hasNext()) {
            return "[]";
        }

        StringBuilder str = new StringBuilder();
        str.append("[");
        while (true) {
            Object object2 = iterator.next();
            str.append(reflectToString(object2));
            if (!iterator.hasNext()) {
                break;
            }
            str.append(", ");
        }
        str.append("]");
        return str.toString();
    }

    // ??
    if (object instanceof Map<?, ?>) {
        Iterator<?> iterator = ((Map<?, ?>) object).entrySet().iterator();
        if (!iterator.hasNext()) {
            return "{}";
        }

        StringBuilder str = new StringBuilder();
        str.append("{");
        while (true) {
            Object entry = iterator.next();
            str.append(reflectToString(entry));
            if (!iterator.hasNext()) {
                break;
            }
            str.append(", ");
        }
        str.append("}");
        return str.toString();
    }

    // Entry??
    if (object instanceof Entry<?, ?>) {
        Entry<?, ?> entry = (Entry<?, ?>) object;
        StringBuilder str = new StringBuilder();
        str.append(reflectToString(entry.getKey()));
        str.append("=");
        str.append(reflectToString(entry.getValue()));
        return str.toString();
    }

    // toString?????
    try {
        Method method = object.getClass().getMethod("toString");
        if (!Object.class.equals(method.getDeclaringClass())) {
            return object.toString();
        }
    } catch (NoSuchMethodException ignore) {
    }

    // ?????
    try {
        PropertyDescriptor[] descriptors = Introspector.getBeanInfo(object.getClass()).getPropertyDescriptors();
        StringBuilder str = new StringBuilder();
        str.append("[");
        for (PropertyDescriptor descriptor : descriptors) {
            if ("class".equals(descriptor.getName())) {
                continue;
            }

            Method readMethod = descriptor.getReadMethod();
            if (readMethod == null) {
                continue;
            }

            if (str.length() > 1) {
                str.append(", ");
            }
            Object object2 = readMethod.invoke(object);
            str.append(descriptor.getName()).append("=").append(reflectToString(object2));
        }
        str.append("]");
        return str.toString();
    } catch (IntrospectionException ignore) {
    } catch (InvocationTargetException ignore) {
    } catch (IllegalAccessException ignore) {
    }

    // ????????commons-lang?
    return ReflectionToStringBuilder.toString(object);
}

From source file:org.onebusaway.nyc.presentation.impl.NycConfigurationServiceImpl.java

private ConfigurationBean loadSettings() {

    if (_path == null || !_path.exists())
        return new ConfigurationBean();

    try {// w w  w  . j ava  2 s  .c om

        Properties properties = new Properties();
        properties.load(new FileReader(_path));

        ConfigurationBean bean = new ConfigurationBean();
        BeanInfo beanInfo = Introspector.getBeanInfo(ConfigurationBean.class);

        for (PropertyDescriptor desc : beanInfo.getPropertyDescriptors()) {
            String name = desc.getName();
            Object value = properties.getProperty(name);
            if (value != null) {
                Converter converter = ConvertUtils.lookup(desc.getPropertyType());
                value = converter.convert(desc.getPropertyType(), value);
                Method m = desc.getWriteMethod();
                m.invoke(bean, value);
            }
        }

        return bean;
    } catch (Exception ex) {
        throw new IllegalStateException("error loading configuration from properties file " + _path, ex);
    }
}

From source file:org.opendaylight.controller.cluster.datastore.DatastoreContextIntrospector.java

/**
 * Introspects the DataStoreProperties interface that is generated from the DataStoreProperties
 * yang grouping. We use the bean Introspector to find the types of all the properties defined
 * in the interface (this is the type returned from the getter method). For each type, we find
 * the appropriate constructor that we will use.
 *///from  w ww  .  ja  v a  2s  . co  m
private static void introspectDataStoreProperties() throws IntrospectionException {
    BeanInfo beanInfo = Introspector.getBeanInfo(DataStoreProperties.class);
    for (PropertyDescriptor desc : beanInfo.getPropertyDescriptors()) {
        processDataStoreProperty(desc.getName(), desc.getPropertyType());
    }

    // Getter methods that return Boolean and start with "is" instead of "get" aren't recognized as
    // properties and thus aren't returned from getPropertyDescriptors. A getter starting with
    // "is" is only supported if it returns primitive boolean. So we'll check for these via
    // getMethodDescriptors.
    for (MethodDescriptor desc : beanInfo.getMethodDescriptors()) {
        String methodName = desc.getName();
        if (Boolean.class.equals(desc.getMethod().getReturnType()) && methodName.startsWith("is")) {
            String propertyName = WordUtils.uncapitalize(methodName.substring(2));
            processDataStoreProperty(propertyName, Boolean.class);
        }
    }
}

From source file:org.jkcsoft.java.util.Beans.java

public static PropertyDescriptor getPropertyDescriptor(Object bean, String propName)
        throws IntrospectionException {
    BeanInfo bi = Introspector.getBeanInfo(bean.getClass());
    PropertyDescriptor pds[] = bi.getPropertyDescriptors();
    PropertyDescriptor pd = null;
    for (int i = 0; i < pds.length; i++) {
        if (propName.equalsIgnoreCase(pds[i].getName())) {
            pd = pds[i];//from   w  w  w .j  a va  2  s. c  o m
            break;
        }
    }
    return pd;
}

From source file:org.tros.utils.PropertiesInitializer.java

/**
 * Copy values from the specified object.
 *
 * @param cb//w  ww.  java 2  s .c om
 */
public void copy(PropertiesInitializer cb) {
    try {
        PropertyDescriptor[] thisProps = Introspector.getBeanInfo(this.getClass()).getPropertyDescriptors();
        PropertyDescriptor[] cbProps = Introspector.getBeanInfo(cb.getClass()).getPropertyDescriptors();
        for (PropertyDescriptor thisP : thisProps) {
            for (PropertyDescriptor cbP : cbProps) {
                if (thisP.getName().equals(cbP.getName())
                        && thisP.getPropertyType().equals(cbP.getPropertyType())
                        && thisP.getWriteMethod() != null && cbP.getReadMethod() != null) {
                    thisP.getWriteMethod().invoke(this, cbP.getReadMethod().invoke(cb));
                }
            }
        }
    } catch (IntrospectionException | IllegalAccessException | IllegalArgumentException
            | InvocationTargetException ex) {
        LOGGER.warn(null, ex);
    }
}

From source file:com.emc.ecs.sync.config.ConfigWrapper.java

public ConfigWrapper(Class<C> targetClass) {
    try {//from   w  ww  . ja v a  2 s . c o m
        this.targetClass = targetClass;
        if (targetClass.isAnnotationPresent(StorageConfig.class))
            this.uriPrefix = targetClass.getAnnotation(StorageConfig.class).uriPrefix();
        if (targetClass.isAnnotationPresent(FilterConfig.class))
            this.cliName = targetClass.getAnnotation(FilterConfig.class).cliName();
        if (targetClass.isAnnotationPresent(Label.class))
            this.label = targetClass.getAnnotation(Label.class).value();
        if (targetClass.isAnnotationPresent(Documentation.class))
            this.documentation = targetClass.getAnnotation(Documentation.class).value();
        BeanInfo beanInfo = Introspector.getBeanInfo(targetClass);
        for (PropertyDescriptor descriptor : beanInfo.getPropertyDescriptors()) {
            if (descriptor.getReadMethod().isAnnotationPresent(Option.class)) {
                propertyMap.put(descriptor.getName(), new ConfigPropertyWrapper(descriptor));
            }
        }
        for (MethodDescriptor descriptor : beanInfo.getMethodDescriptors()) {
            Method method = descriptor.getMethod();
            if (method.isAnnotationPresent(UriParser.class)) {
                if (method.getReturnType().equals(Void.TYPE) && method.getParameterTypes().length == 1
                        && method.getParameterTypes()[0].equals(String.class)) {
                    uriParser = method;
                } else {
                    log.warn("illegal signature for @UriParser method {}.{}", targetClass.getSimpleName(),
                            method.getName());
                }
            } else if (method.isAnnotationPresent(UriGenerator.class)) {
                if (method.getReturnType().equals(String.class) && method.getParameterTypes().length == 0) {
                    uriGenerator = method;
                } else {
                    log.warn("illegal signature for @UriGenerator method {}.{}", targetClass.getSimpleName(),
                            method.getName());
                }
            }
        }
        if (propertyMap.isEmpty())
            log.info("no @Option annotations found in {}", targetClass.getSimpleName());
    } catch (IntrospectionException e) {
        throw new RuntimeException(e);
    }
}

From source file:com.bstek.dorado.config.ExpressionMethodInterceptor.java

protected void discoverInterceptingMethods(Class<?> clazz) throws Exception {
    interceptingReadMethods = new HashMap<Method, ReadMethodDescriptor>();
    interceptingWriteMethods = new HashMap<Method, Method>();
    Map<Method, ReadMethodDescriptor> getterMethods = interceptingReadMethods;
    Map<Method, Method> setterMethods = interceptingWriteMethods;
    Map<String, Expression> expressionProperties = getExpressionProperties();

    BeanInfo beanInfo = Introspector.getBeanInfo(clazz);
    PropertyDescriptor[] propertyDescriptors = beanInfo.getPropertyDescriptors();
    for (PropertyDescriptor propertyDescriptor : propertyDescriptors) {
        String property = propertyDescriptor.getName();
        if (expressionProperties.containsKey(property)) {
            Method readMethod = propertyDescriptor.getReadMethod();
            Method writeMethod = propertyDescriptor.getWriteMethod();

            if (readMethod != null) {
                if (readMethod.getDeclaringClass() != clazz) {
                    readMethod = clazz.getMethod(readMethod.getName(), readMethod.getParameterTypes());
                }//from  w  w w.  j  av a 2s  .  co  m
                getterMethods.put(readMethod, new ReadMethodDescriptor(property, null));
            }
            if (writeMethod != null) {
                if (writeMethod.getDeclaringClass() != clazz) {
                    writeMethod = clazz.getMethod(writeMethod.getName(), writeMethod.getParameterTypes());
                }
                setterMethods.put(writeMethod, readMethod);
            }
        }
    }
}

From source file:org.eclipse.nebula.widgets.nattable.data.ReflectiveColumnPropertyAccessor.java

private PropertyDescriptor getPropertyDescriptor(R rowObj, int columnIndex) throws IntrospectionException {
    if (propertyDescriptorMap == null) {
        propertyDescriptorMap = new HashMap<String, PropertyDescriptor>();
        PropertyDescriptor[] propertyDescriptors = Introspector.getBeanInfo(rowObj.getClass())
                .getPropertyDescriptors();
        for (PropertyDescriptor propertyDescriptor : propertyDescriptors) {
            propertyDescriptorMap.put(propertyDescriptor.getName(), propertyDescriptor);
        }//w w w.j a v  a2 s.  c om
    }

    final String propertyName = propertyNames.get(columnIndex);
    return propertyDescriptorMap.get(propertyName);
}

From source file:eu.squadd.reflections.mapper.ServiceModelTranslator.java

/**
 * this is Java Reflections translation method doing the magic where JAXB cannot
 * it is type independent as long as it is a valid java object
 * it cannot be an interface, abstract class and cannot use generics     
 * //from   w  w w . j  a  va 2 s.c  o m
 * @param <T>
 * @param sourceClass   - type of the source object
 * @param destClass     - type of destination object
 * @param source        - source object itself
 * @return              - translated destination object
 */
public static <T> T transposeModel(Class sourceClass, Class<T> destClass, Object source) {
    Object destInstance = null;
    try {
        destInstance = ConstructorUtils.invokeConstructor(destClass, null);
        BeanInfo destInfo = Introspector.getBeanInfo(destClass);
        PropertyDescriptor[] destProps = destInfo.getPropertyDescriptors();

        BeanInfo sourceInfo = Introspector.getBeanInfo(sourceClass, Object.class);
        PropertyDescriptor[] sourceProps = sourceInfo.getPropertyDescriptors();

        for (PropertyDescriptor sourceProp : sourceProps) {
            String name = sourceProp.getName();
            Method getter = sourceProp.getReadMethod();
            Class<?> sType;
            try {
                sType = sourceProp.getPropertyType();
            } catch (NullPointerException ex) {
                System.err
                        .println("The type of source field cannot be determined, field skipped, name: " + name);
                continue;
            }
            Object sValue;
            try {
                sValue = getter.invoke(source);
            } catch (NullPointerException ex) {
                System.err.println("Cannot obtain the value from field, field skipped, name: " + name);
                continue;
            }
            for (PropertyDescriptor destProp : destProps) {
                if (destProp.getName().equals(name)) {
                    if (assignPropertyValue(sourceProp, sValue, destProp, destInstance))
                        System.out.println(
                                "Destination property assigned, source name: " + name + ", type: " + sType);
                    else
                        System.err.println(
                                "Failed to assign property, source name: " + name + ", type: " + sType);

                    break;
                }
            }
        }
    } catch (InvocationTargetException | IntrospectionException | IllegalAccessException
            | IllegalArgumentException | NoSuchMethodException | InstantiationException ex) {
        Logger.getLogger(ServiceModelTranslator.class.getName()).log(Level.SEVERE, null, ex);
    }
    return destClass.cast(destInstance);
}