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.github.mrgoro.interactivedata.spring.service.SwaggerService.java

/**
 * Get Parameters from a// w ww.  j a  v a  2  s . co  m
 * {@link com.github.mrgoro.interactivedata.api.data.operations.OperationData OperationData}-Class.
 *
 * @param dataClass Operation Data Class
 * @param type Type of operation
 * @return Map of parameters with their names as keys
 */
private Map<String, Parameter> getParametersForClass(Class<?> dataClass, String type) {
    Map<String, Parameter> parameters = new HashMap<>();
    try {
        PropertyDescriptor[] propertyDescriptors = Introspector.getBeanInfo(dataClass).getPropertyDescriptors();
        for (PropertyDescriptor pd : propertyDescriptors) {
            // Class is a property descriptor => filter out
            if (pd.getReadMethod() != null && !"class".equals(pd.getName())) {
                parameters.put(pd.getName(),
                        new QueryParameter().name(pd.getName()).description(type + " param for " + pd.getName())
                                .required(false).property(getProperty(pd.getPropertyType())));
            }
        }
    } catch (IntrospectionException e) {
        log.error("Exception using introspection for generating Interactive Data API (Parameters)", e);
    }
    return parameters;
}

From source file:org.pentaho.reporting.engine.classic.core.modules.parser.ext.factory.base.BeanObjectDescription.java

private void readBeanDescription(final Class className, final boolean init) {
    try {/*from w w  w  .j  a va  2 s .c o m*/
        this.properties = new HashMap();

        final BeanInfo bi = Introspector.getBeanInfo(className);
        final PropertyDescriptor[] propertyDescriptors = bi.getPropertyDescriptors();
        for (int i = 0; i < propertyDescriptors.length; i++) {
            final PropertyDescriptor propertyDescriptor = propertyDescriptors[i];
            final Method readMethod = propertyDescriptor.getReadMethod();
            final Method writeMethod = propertyDescriptor.getWriteMethod();
            if (isValidMethod(readMethod, 0) && isValidMethod(writeMethod, 1)) {
                final String name = propertyDescriptor.getName();
                this.properties.put(name, propertyDescriptor);
                if (init) {
                    super.setParameterDefinition(name, propertyDescriptor.getPropertyType());
                }
            }
        }
    } catch (IntrospectionException e) {
        BeanObjectDescription.logger.error("Unable to build bean description", e);
    }
}

From source file:org.hx.rainbow.common.util.JavaBeanUtil.java

@SuppressWarnings("rawtypes")
private static Map<String, Class> getFileds(Class clazz) {
    BeanInfo beanInfo = null;/* ww  w.j av a  2  s  . c o  m*/
    try {
        beanInfo = Introspector.getBeanInfo(clazz);
    } catch (IntrospectionException e) {
        e.printStackTrace();
    }
    Map<String, Class> map = new HashMap<String, Class>();
    PropertyDescriptor[] pr = beanInfo.getPropertyDescriptors();
    for (int i = 1; i < pr.length; i++) {
        map.put(pr[i].getName(), pr[i].getPropertyType());
    }
    Field[] field = clazz.getDeclaredFields();
    for (int i = 1; i < field.length; i++) {
        map.put(field[i].getName(), field[i].getType());
    }
    return map;
}

From source file:org.fhcrc.cpl.toolbox.datastructure.BoundMap.java

private void initialize(Class beanClass) {
    synchronized (_savedPropertyMaps) {
        HashMap<String, BoundProperty> props = _savedPropertyMaps.get(beanClass);
        if (props == null) {
            try {
                props = new HashMap<String, BoundProperty>();
                BeanInfo beanInfo = Introspector.getBeanInfo(beanClass);
                PropertyDescriptor[] propertyDescriptors = beanInfo.getPropertyDescriptors();
                if (propertyDescriptors != null) {
                    for (PropertyDescriptor propertyDescriptor : propertyDescriptors) {
                        if (propertyDescriptor != null) {
                            String name = propertyDescriptor.getName();
                            if ("class".equals(name))
                                continue;
                            Method readMethod = propertyDescriptor.getReadMethod();
                            Method writeMethod = propertyDescriptor.getWriteMethod();
                            Class aType = propertyDescriptor.getPropertyType();
                            props.put(name, new BoundProperty(readMethod, writeMethod, aType));
                        }/* w w  w .j ava2s . c o m*/
                    }
                }
            } catch (IntrospectionException e) {
                Logger.getLogger(this.getClass()).error("error creating BoundMap", e);
                throw new RuntimeException(e);
            }
            _savedPropertyMaps.put(beanClass, props);
        }
        _properties = props;
    }
}

From source file:edu.harvard.med.screensaver.model.AbstractEntityInstanceTest.java

/**
 * Subclasses should call this method to build their TestSuite, as it will
 * include tests for the test methods declared in this class, as well as tests
 * for each entity property found in the specified AbstractEntity class.
 * //from   ww w  .  j a v  a 2 s  .co  m
 * @param entityTestClass
 * @param entityClass
 * @return
 */
public static TestSuite buildTestSuite(Class<? extends AbstractEntityInstanceTest> entityTestClass,
        Class<? extends AbstractEntity> entityClass) {
    TestSuite testSuite = new TestSuite(entityTestClass);
    BeanInfo beanInfo;
    try {
        beanInfo = Introspector.getBeanInfo(entityClass);
        // add all the property-specific tests for this entity class
        for (PropertyDescriptor propertyDescriptor : beanInfo.getPropertyDescriptors()) {
            if (propertyDescriptor.getName().equals("class")) {
                log.debug("not creating test for \"class\" property " + propertyDescriptor.getDisplayName());
            } else if (ModelIntrospectionUtil.isTransientProperty(propertyDescriptor)) {
                log.debug("not creating test for transient (non-persistent) property "
                        + propertyDescriptor.getDisplayName());
            } else /*if (ModelIntrospectionUtil.isToManyEntityRelationship(propertyDescriptor))*/ {
                propertyDescriptor = new GenericTypeAwarePropertyDescriptor(entityClass, propertyDescriptor);
                testSuite.addTest(new EntityPropertyTest(entityClass, propertyDescriptor));
            }
        }
    } catch (IntrospectionException e) {
        e.printStackTrace();
        fail(e.getMessage());
    }
    return testSuite;
}

From source file:org.gerzog.jstataggr.writers.csv.CSVStatisticsWriter.java

protected BeanInfo getBeanInfo(final Object object) {
    return propogate(() -> Introspector.getBeanInfo(object.getClass()));
}

From source file:no.sesat.search.datamodel.DataModelFactoryImplTest.java

private void scan(final Class<? extends Annotation> type, final Class<?> cls, final Command command)
        throws IntrospectionException {

    LOG.info("scanning " + cls.getSimpleName());
    final PropertyDescriptor[] properties = Introspector.getBeanInfo(cls).getPropertyDescriptors();
    for (PropertyDescriptor property : properties) {

        final Class<?> propCls = property instanceof MappedPropertyDescriptor
                ? ((MappedPropertyDescriptor) property).getMappedPropertyType()
                : property.getPropertyType();

        LOG.info("  checking property " + property.getName() + " [" + propCls.getSimpleName() + ']');

        if (null != propCls.getAnnotation(type)) {
            command.execute(propCls);/* ww w  .j a  va  2 s.c  om*/
        }

        if (null != propCls.getAnnotation(DataNode.class)) {
            // also descend down dataNodes in the datamodel
            scan(type, propCls, command);
        }
    }

    // repeat again on all implemented interfaces
    for (Class<?> c : cls.getInterfaces()) {
        scan(type, c, command);
    }
}

From source file:org.eclipse.scada.configuration.recipe.lib.internal.DefaultExecutableFactory.java

protected void captureOutput(final Object o, final RunnerContext ctx, final EList<CaptureOutput> outputs)
        throws Exception {
    here: for (final CaptureOutput output : outputs) {
        final String name = output.getLocalName();
        final String storeName = output.getContextName() == null ? name : output.getContextName();

        logger.debug("Capture output: {} -> {}", name, storeName);

        final BeanInfo bi = Introspector.getBeanInfo(o.getClass());
        for (final PropertyDescriptor pd : bi.getPropertyDescriptors()) {
            if (pd.getName().equals(name)) {
                final Object value = pd.getReadMethod().invoke(o);
                ctx.getMap().put(storeName, value);
                logger.debug("By BeanInfo - value: {}", value);
                continue here;
            }//from   w w w  . j  a  va2  s  .c  om
        }

        final Field field = Reflections.findField(o.getClass(), name);
        if (field != null && field.getAnnotation(Output.class) != null) {
            final Object value = InjectHelper.getField(o, field);
            ctx.getMap().put(storeName, value);
            logger.debug("By field - value: {}", value);
            continue;
        }
        if (field != null) {
            throw new IllegalStateException(String.format(
                    "Unable to capture output. Field '%s' of class '%s' is not marked with @Output and is not accessible using a getter."));
        }

        throw new IllegalStateException(
                String.format("Unable to capture output '%s' of class '%s'", name, o.getClass()));
    }
}

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

/**
 * Obtiene el valor de la propiedad de un Bean
 *
 * @param obj El objeto Bean/*ww w.ja  v  a2  s. co  m*/
 * @param propertyName El nombre de la propiedad. Se permiten
 * "subpropiedades" separadas por "."
 * @return El valor de la propiedad
 */
static public Object getValueFromBean(Object obj, String propertyName) {
    try {
        Object value;

        BeanInfo beanInfo = Introspector.getBeanInfo(obj.getClass());
        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 antes 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");
        }

        Method readMethod = null;
        for (PropertyDescriptor propertyDescriptor : propertyDescriptors) {
            if (propertyDescriptor.getName().equals(leftPropertyName)) {
                readMethod = propertyDescriptor.getReadMethod();
            }
        }

        if (readMethod == null) {
            throw new RuntimeException("No existe la propiedad:" + leftPropertyName);
        }

        if (rigthPropertyName != null) {
            Object valueProperty = readMethod.invoke(obj);
            value = getValueFromBean(valueProperty, rigthPropertyName);
        } else {
            value = readMethod.invoke(obj);
        }

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

From source file:com.boylesoftware.web.impl.UserInputControllerMethodArgHandler.java

/**
 * Create new handler./*  w w  w  .ja  v  a  2s  .  co  m*/
 *
 * @param validatorFactory Validator factory.
 * @param beanClass User input bean class.
 * @param validationGroups Validation groups to apply during bean
 * validation, or empty array to use the default group.
 *
 * @throws UnavailableException If an error happens.
 */
UserInputControllerMethodArgHandler(final ValidatorFactory validatorFactory, final Class<?> beanClass,
        final Class<?>[] validationGroups) throws UnavailableException {

    this.validatorFactory = validatorFactory;

    this.beanClass = beanClass;
    this.validationGroups = validationGroups;

    try {
        final BeanInfo beanInfo = Introspector.getBeanInfo(this.beanClass);
        final PropertyDescriptor[] propDescs = beanInfo.getPropertyDescriptors();
        final List<FieldDesc> beanFields = new ArrayList<>();
        for (final PropertyDescriptor propDesc : propDescs) {
            final String propName = propDesc.getName();
            final Class<?> propType = propDesc.getPropertyType();
            final Method propGetter = propDesc.getReadMethod();
            final Method propSetter = propDesc.getWriteMethod();

            if ((propGetter == null) || (propSetter == null))
                continue;

            Field propField = null;
            for (Class<?> c = this.beanClass; !c.equals(Object.class); c = c.getSuperclass()) {
                try {
                    propField = c.getDeclaredField(propName);
                    break;
                } catch (final NoSuchFieldException e) {
                    // nothing, continue the loop
                }
            }
            final boolean noTrim = (((propField != null) && propField.isAnnotationPresent(NoTrim.class))
                    || (propGetter.isAnnotationPresent(NoTrim.class)));

            Class<? extends Binder> binderClass = null;
            String format = null;
            String errorMessage = Bind.DEFAULT_MESSAGE;
            Bind bindAnno = null;
            if (propField != null)
                bindAnno = propField.getAnnotation(Bind.class);
            if (bindAnno == null)
                bindAnno = propGetter.getAnnotation(Bind.class);
            if (bindAnno != null) {
                binderClass = bindAnno.binder();
                format = bindAnno.format();
                errorMessage = bindAnno.message();
            }
            if (binderClass == null) {
                if ((String.class).isAssignableFrom(propType))
                    binderClass = StringBinder.class;
                else if ((Boolean.class).isAssignableFrom(propType) || propType.equals(Boolean.TYPE))
                    binderClass = BooleanBinder.class;
                else if ((Integer.class).isAssignableFrom(propType) || propType.equals(Integer.TYPE))
                    binderClass = IntegerBinder.class;
                else if (propType.isEnum())
                    binderClass = EnumBinder.class;
                else // TODO: add more standard binders
                    throw new UnavailableException(
                            "Unsupported user input bean field type " + propType.getName() + ".");
            }

            beanFields.add(new FieldDesc(propDesc, noTrim, binderClass.newInstance(), format, errorMessage));
        }
        this.beanFields = beanFields.toArray(new FieldDesc[beanFields.size()]);
    } catch (final IntrospectionException e) {
        this.log.error("error introspecting user input bean", e);
        throw new UnavailableException("Specified user input bean" + " class could not be introspected.");
    } catch (final IllegalAccessException | InstantiationException e) {
        this.log.error("error instatiating binder", e);
        throw new UnavailableException("Used user input bean field binder" + " could not be instantiated.");
    }

    this.beanPool = new FastPool<>(new PoolableObjectFactory<PoolableUserInput>() {

        @Override
        public PoolableUserInput makeNew(final FastPool<PoolableUserInput> pool, final int pooledObjectId) {

            try {
                return new PoolableUserInput(pool, pooledObjectId, beanClass.newInstance());
            } catch (final InstantiationException | IllegalAccessException e) {
                throw new RuntimeException("Error instatiating user input bean.", e);
            }
        }
    }, "UserInputBeansPool_" + beanClass.getSimpleName());
}