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:de.knightsoftnet.validators.rebind.GwtSpecificValidatorCreator.java

private void writeFields(final SourceWriter sw) throws UnableToCompleteException {

    // Create a static array of all valid property names.
    BeanInfo beanInfo;/*from ww w  .  j av  a 2 s.  c o  m*/
    try {
        beanInfo = Introspector.getBeanInfo(this.beanHelper.getClazz());
    } catch (final IntrospectionException e) {
        throw error(this.logger, e);
    }

    // private static final java.util.List<String> ALL_PROPERTY_NAMES =
    sw.println("private static final java.util.List<String> ALL_PROPERTY_NAMES = ");
    sw.indent();
    sw.indent();

    // Collections.<String>unmodifiableList(
    sw.println("java.util.Collections.<String>unmodifiableList(");
    sw.indent();
    sw.indent();

    // java.util.Arrays.<String>asList(
    sw.print("java.util.Arrays.<String>asList(");

    // "foo","bar" );
    sw.print(Joiner.on(",").join(Iterables.transform(ImmutableList.copyOf(beanInfo.getPropertyDescriptors()),
            Functions.compose(TO_LITERAL, PROPERTY_DESCRIPTOR_TO_NAME))));
    sw.println("));");
    sw.outdent();
    sw.outdent();
    sw.outdent();
    sw.outdent();

    // Write the metadata for the bean
    this.writeBeanMetadata(sw);
    sw.println();

    // Create a variable for each constraint of each property
    for (final PropertyDescriptor p : this.beanHelper.getBeanDescriptor().getConstrainedProperties()) {
        int count = 0;
        for (final ConstraintDescriptor<?> constraint : p.getConstraintDescriptors()) {
            final org.hibernate.validator.internal.metadata.descriptor.ConstraintDescriptorImpl<?> constraintHibernate = (org.hibernate.validator.internal.metadata.descriptor.ConstraintDescriptorImpl<?>) constraint;
            if (this.areConstraintDescriptorGroupsValid(constraint)) {
                this.writeConstraintDescriptor(sw, constraint, constraintHibernate.getElementType(),
                        convertConstraintOriginEnum(constraintHibernate.getDefinedOn()),
                        this.constraintDescriptorVar(p.getPropertyName(), count++));
            }
        }
        this.writePropertyDescriptor(sw, p);
        if (p.isCascaded()) {
            this.beansToValidate.add(isIterableOrMap(p.getElementClass())
                    ? this.createBeanHelper(this.beanHelper.getAssociationType(p, true))
                    : this.createBeanHelper(p.getElementClass()));
        }
    }

    // Create a variable for each constraint of this class.
    int count = 0;
    for (final ConstraintDescriptor<?> constraint : this.beanHelper.getBeanDescriptor()
            .getConstraintDescriptors()) {
        final org.hibernate.validator.internal.metadata.descriptor.ConstraintDescriptorImpl<?> constraintHibernate = (org.hibernate.validator.internal.metadata.descriptor.ConstraintDescriptorImpl<?>) constraint;
        if (this.areConstraintDescriptorGroupsValid(constraint)) {
            this.writeConstraintDescriptor(sw, constraint, ElementType.TYPE,
                    convertConstraintOriginEnum(constraintHibernate.getDefinedOn()),
                    this.constraintDescriptorVar("this", count++));
        }
    }

    // Now write the BeanDescriptor after we already have the
    // PropertyDescriptors and class constraints
    this.writeBeanDescriptor(sw);
    sw.println();
}

From source file:org.wings.SComponent.java

/**
 * Generates a string describing this <code>SComponent</code>.
 * This method is mainly for debugging purposes.
 *
 * @return a string containing all properties
 *//*from   www. j  av a2 s . c o m*/
protected String paramString() {
    StringBuilder buffer = new StringBuilder(getClass().getName());
    buffer.append("[");

    try {
        BeanInfo info = Introspector.getBeanInfo(getClass());
        PropertyDescriptor[] descriptors = info.getPropertyDescriptors();

        boolean first = true;
        for (PropertyDescriptor descriptor : descriptors) {
            try {
                Method getter = descriptor.getReadMethod();
                if (getter == null || getter.getName().startsWith("getParent")) {
                    continue;
                }
                // System.out.println("invoking " + this.getClass().getDescription()+"."+getter.getDescription());
                Object value = getter.invoke(this);
                if (first) {
                    first = false;
                } else {
                    buffer.append(",");
                }
                buffer.append(descriptor.getName() + "=" + value);
            } catch (Exception e) {
                log.debug("Exception during paramString()" + e);
            }
        }
    } catch (Exception e) {
        log.debug("Exception during paramString()" + e);
    }

    buffer.append("]");
    return buffer.toString();
}

From source file:org.quartz.impl.StdSchedulerFactory.java

private void setBeanProps(Object obj, Properties props) throws NoSuchMethodException, IllegalAccessException,
        java.lang.reflect.InvocationTargetException, IntrospectionException, SchedulerConfigException {
    props.remove("class");

    BeanInfo bi = Introspector.getBeanInfo(obj.getClass());
    PropertyDescriptor[] propDescs = bi.getPropertyDescriptors();
    PropertiesParser pp = new PropertiesParser(props);

    java.util.Enumeration keys = props.keys();
    while (keys.hasMoreElements()) {
        String name = (String) keys.nextElement();
        String c = name.substring(0, 1).toUpperCase(Locale.US);
        String methName = "set" + c + name.substring(1);

        java.lang.reflect.Method setMeth = getSetMethod(methName, propDescs);

        try {/*  w w  w  .j av a 2 s. c o  m*/
            if (setMeth == null) {
                throw new NoSuchMethodException("No setter for property '" + name + "'");
            }

            Class[] params = setMeth.getParameterTypes();
            if (params.length != 1) {
                throw new NoSuchMethodException("No 1-argument setter for property '" + name + "'");
            }
            if (params[0].equals(int.class)) {
                setMeth.invoke(obj, new Object[] { new Integer(pp.getIntProperty(name)) });
            } else if (params[0].equals(long.class)) {
                setMeth.invoke(obj, new Object[] { new Long(pp.getLongProperty(name)) });
            } else if (params[0].equals(float.class)) {
                setMeth.invoke(obj, new Object[] { new Float(pp.getFloatProperty(name)) });
            } else if (params[0].equals(double.class)) {
                setMeth.invoke(obj, new Object[] { new Double(pp.getDoubleProperty(name)) });
            } else if (params[0].equals(boolean.class)) {
                setMeth.invoke(obj, new Object[] { new Boolean(pp.getBooleanProperty(name)) });
            } else if (params[0].equals(String.class)) {
                setMeth.invoke(obj, new Object[] { pp.getStringProperty(name) });
            } else {
                throw new NoSuchMethodException("No primitive-type setter for property '" + name + "'");
            }
        } catch (NumberFormatException nfe) {
            throw new SchedulerConfigException(
                    "Could not parse property '" + name + "' into correct data type: " + nfe.toString());
        }
    }
}

From source file:org.eclipse.wb.internal.core.utils.reflect.ReflectionUtils.java

/**
 * @return the {@link BeanInfo} of given component {@link Class}.
 *///from w  w  w. j av a2s. c  o m
public static BeanInfo getBeanInfo(Class<?> clazz) throws IntrospectionException {
    // standard components don't have BeanInfo's
    {
        String className = clazz.getName();
        if (className.startsWith("java.lang.") || className.startsWith("java.awt.")
                || className.startsWith("javax.swing.") || className.startsWith("org.eclipse.swt")
                || className.startsWith("org.eclipse.jface") || className.startsWith("org.eclipse.ui.forms")) {
            return null;
        }
    }
    // OK, get BeanInfo (may be not trivial)
    Introspector.flushCaches();
    String[] standard_beanInfoSearchPath = Introspector.getBeanInfoSearchPath();
    try {
        Introspector.setBeanInfoSearchPath(new String[] {});
        return Introspector.getBeanInfo(clazz);
    } finally {
        Introspector.flushCaches();
        Introspector.setBeanInfoSearchPath(standard_beanInfoSearchPath);
    }
}

From source file:org.schemaspy.Config.java

/**
 * Call all the getters to populate all the lazy initialized stuff.
 *
 * @throws InvocationTargetException/*from www. j a v  a  2 s.  c  om*/
 * @throws IllegalAccessException
 * @throws IllegalArgumentException
 * @throws IntrospectionException
 */
private void populate() throws IllegalArgumentException, IllegalAccessException, InvocationTargetException,
        IntrospectionException {
    if (!populating) { // prevent recursion
        populating = true;

        BeanInfo beanInfo = Introspector.getBeanInfo(Config.class);
        PropertyDescriptor[] props = beanInfo.getPropertyDescriptors();
        for (int i = 0; i < props.length; ++i) {
            Method readMethod = props[i].getReadMethod();
            if (readMethod != null)
                readMethod.invoke(this, (Object[]) null);
        }

        populating = false;
    }
}

From source file:weka.classifiers.timeseries.eval.TSEvaluation.java

/**
 * Return the global info (if it exists) for the supplied forecaster.
 * /*w  w  w.j  ava  2s.c  o  m*/
 * @param forecaster the forecaster to get the global info for
 * @return the global info (synopsis) for the classifier
 * @throws Exception if there is a problem reflecting on the forecaster
 */
protected static String getGlobalInfo(TSForecaster forecaster) throws Exception {
    BeanInfo bi = Introspector.getBeanInfo(forecaster.getClass());
    MethodDescriptor[] methods;
    methods = bi.getMethodDescriptors();
    Object[] args = {};
    String result = "\nSynopsis for " + forecaster.getClass().getName() + ":\n\n";

    for (int i = 0; i < methods.length; i++) {
        String name = methods[i].getDisplayName();
        Method meth = methods[i].getMethod();
        if (name.equals("globalInfo")) {
            String globalInfo = (String) (meth.invoke(forecaster, args));
            result += globalInfo;
            break;
        }
    }

    return result;
}

From source file:org.schemaspy.Config.java

/**
 * Get the value of the specified parameter.
 * Used for properties that are common to most db's, but aren't required.
 *
 * @param paramName/*from ww w.  j av a 2 s .c o  m*/
 * @return
 */
public String getParam(String paramName) {
    try {
        BeanInfo beanInfo = Introspector.getBeanInfo(Config.class);
        PropertyDescriptor[] props = beanInfo.getPropertyDescriptors();
        for (int i = 0; i < props.length; ++i) {
            PropertyDescriptor prop = props[i];
            if (prop.getName().equalsIgnoreCase(paramName)) {
                Object result = prop.getReadMethod().invoke(this, (Object[]) null);
                return result == null ? null : result.toString();
            }
        }
    } catch (Exception failed) {
        failed.printStackTrace();
    }

    return null;
}

From source file:com.dell.asm.asmcore.asmmanager.app.rest.ServiceTemplateService.java

public static <M> void merge(M target, M source) {
    try {/*from  ww  w. j  a  v a2 s.co m*/
        final BeanInfo beanInfo = Introspector.getBeanInfo(target.getClass());

        // Iterate over all the attributes
        for (final PropertyDescriptor descriptor : beanInfo.getPropertyDescriptors()) {
            // Only copy writable attributes
            if (descriptor.getWriteMethod() != null) {
                final Object originalValue = descriptor.getReadMethod().invoke(target);
                // Only copy values values where the destination values is null
                if (originalValue == null) {
                    final Object defaultValue = descriptor.getReadMethod().invoke(source);
                    descriptor.getWriteMethod().invoke(target, defaultValue);
                }
            }
        }
    } catch (IntrospectionException | IllegalAccessException | IllegalArgumentException
            | InvocationTargetException e) {
        throw new RuntimeException(e);
    }
}