Example usage for java.beans PropertyDescriptor getReadMethod

List of usage examples for java.beans PropertyDescriptor getReadMethod

Introduction

In this page you can find the example usage for java.beans PropertyDescriptor getReadMethod.

Prototype

public synchronized Method getReadMethod() 

Source Link

Document

Gets the method that should be used to read the property value.

Usage

From source file:net.kamhon.ieagle.util.CollectionUtil.java

private static Object processForNumber(Object object, String propertyName, Object propValue) {
    BeanWrapper wrapper = new BeanWrapperImpl(object);
    PropertyDescriptor descriptor = wrapper.getPropertyDescriptor(propertyName);
    Method method = descriptor.getReadMethod();
    TypeConversion typeConversion = method.getAnnotation(TypeConversion.class);
    if (typeConversion != null) {
        String convertor = typeConversion.converter();
        if (convertor.equalsIgnoreCase(FrameworkConst.STRUTS_DECIMAL_CONVERTER)) {
            DecimalFormat df = new DecimalFormat(FrameworkConst.DEFAULT_DECIMAL_FORMAT);
            return df.format(propValue);
        } else {//from  ww w . jav  a2s  . c o m
            return propValue;
        }
    } else {
        if (propValue instanceof Double || propValue instanceof Float) {
            DecimalFormat df = new DecimalFormat(FrameworkConst.DEFAULT_DECIMAL_FORMAT);
            return df.format(propValue);
        } else {
            return propValue;
        }
    }
}

From source file:com.ebay.pulsar.analytics.dao.service.BaseDBService.java

public static Map<String, Object> describe(Object obj) {
    if (obj == null) {
        return null;
    }//from  w ww. j a  v  a  2  s. co m
    Map<String, Object> map = new HashMap<String, Object>();
    try {
        BeanInfo beanInfo = Introspector.getBeanInfo(obj.getClass());
        PropertyDescriptor[] propertyDescriptors = beanInfo.getPropertyDescriptors();
        for (PropertyDescriptor property : propertyDescriptors) {
            String key = property.getName();
            if (!key.equals("class")) {
                try {
                    Method getter = property.getReadMethod();
                    Object value = getter.invoke(obj);
                    if (value != null) {

                        if ("properties".equalsIgnoreCase(key) || "config".equalsIgnoreCase(key)) {
                            value = new SerialBlob(((String) value).getBytes());
                        }
                        map.put(key, value);
                    }
                } catch (Exception e) {
                    logger.error("transBean1Map Error " + e);
                }
            }

        }
    } catch (Exception e) {
        logger.error("transBean2Map Error " + e);
    }
    return map;

}

From source file:de.alpharogroup.lang.object.MergeObjectExtensions.java

/**
 * Merge the given property to the given 'to' object with the given 'with' object.
 *
 * @param <TO>/*from   w  w w  .  j  a va2 s  .c om*/
 *            the generic type of the object to merge in
 * @param <WITH>
 *            the generic type of the object to merge with
 * @param toObject
 *            the object to merge in
 * @param withObject
 *            the object to merge with
 * @param propertyDescriptor
 *            the property descriptor
 * @throws InvocationTargetException
 *             if the property accessor method throws an exception
 * @throws IllegalAccessException
 *             if the caller does not have access to the property accessor method
 */
public static final <TO, WITH> void mergeProperty(final TO toObject, final WITH withObject,
        final PropertyDescriptor propertyDescriptor) throws IllegalAccessException, InvocationTargetException {
    if (PropertyUtils.isReadable(toObject, propertyDescriptor.getName())
            && PropertyUtils.isWriteable(toObject, propertyDescriptor.getName())) {
        final Method getter = propertyDescriptor.getReadMethod();
        final Object value = getter.invoke(withObject);
        if (!value.isDefaultValue()) {
            final Method setter = propertyDescriptor.getWriteMethod();
            setter.invoke(toObject, value);
        }
    }
}

From source file:de.iteratec.iteraplan.businesslogic.exchange.common.vbb.impl.util.VisualVariableHelper.java

private static void setMultiplicityAndDataType(EPackage vvEPackage, EAttribute att, PropertyDescriptor pd) {
    if (Collection.class.isAssignableFrom(pd.getPropertyType()) || pd.getPropertyType().isArray()) {
        att.setUpperBound(EStructuralFeature.UNBOUNDED_MULTIPLICITY);
        setMultiplicityAndDataType(vvEPackage, att, pd.getReadMethod().getGenericReturnType());
    } else {//from w ww .j  a  v  a 2 s . co  m
        att.setUpperBound(1);
        setMultiplicityAndDataType(vvEPackage, att, pd.getPropertyType());
    }
}

From source file:com.swingtech.commons.testing.JavaBeanTester.java

/**
 * Tests the get/set methods of the specified class.
 * //from   ww  w. j  a v  a 2 s  .  co m
 * @param <T> the type parameter associated with the class under test
 * @param clazz the Class under test
 * @param skipThese the names of any properties that should not be tested
 * @throws IntrospectionException thrown if the Introspector.getBeanInfo() method throws this exception 
 * for the class under test
 */
public static <T> void test(final Class<T> clazz, final String... skipThese) throws IntrospectionException {
    final PropertyDescriptor[] props = Introspector.getBeanInfo(clazz).getPropertyDescriptors();
    nextProp: for (PropertyDescriptor prop : props) {
        // Check the list of properties that we don't want to test
        for (String skipThis : skipThese) {
            if (skipThis.equals(prop.getName())) {
                continue nextProp;
            }
        }
        final Method getter = prop.getReadMethod();
        final Method setter = prop.getWriteMethod();

        if (getter != null && setter != null) {
            // We have both a get and set method for this property
            final Class<?> returnType = getter.getReturnType();
            final Class<?>[] params = setter.getParameterTypes();

            if (params.length == 1 && params[0] == returnType) {
                // The set method has 1 argument, which is of the same type as the return type of the get method, so we can test this property
                try {
                    // Build a value of the correct type to be passed to the set method
                    Object value = buildValue(returnType);

                    // Build an instance of the bean that we are testing (each property test gets a new instance)
                    T bean = clazz.newInstance();

                    // Call the set method, then check the same value comes back out of the get method
                    setter.invoke(bean, value);

                    final Object expectedValue = value;
                    final Object actualValue = getter.invoke(bean);

                    assertEquals(String.format("Failed while testing property %s", prop.getName()),
                            expectedValue, actualValue);

                } catch (Exception ex) {
                    fail(String.format("An exception was thrown while testing the property %s: %s",
                            prop.getName(), ex.toString()));
                }
            }
        }
    }
}

From source file:com.taobao.rpc.doclet.RPCAPIInfoHelper.java

/**
 * ?/*from  w  ww  .  ja  v  a2  s .  c  om*/
 * 
 * @param method
 * @return
 */
public static Object buildTypeStructure(Class<?> type, Type genericType, Type oriGenericType) {
    if ("void".equalsIgnoreCase(type.getName()) || ClassUtils.isPrimitiveOrWrapper(type)
            || String.class.isAssignableFrom(type) || Date.class.isAssignableFrom(type)
            || URL.class.isAssignableFrom(type)) {
        // 
        return type.getName().replaceAll("java.lang.", "").replaceAll("java.util.", "").replaceAll("java.sql.",
                "");
    } // end if

    if (type.isArray()) {
        // 
        return new Object[] {
                buildTypeStructure(type.getComponentType(), type.getComponentType(), genericType) };
    } // end if

    if (ClassUtils.isAssignable(Map.class, type)) {
        // Map
        return Map.class.getName();
    } // end if

    if (type.isEnum()) {
        // Enum
        return Enum.class.getName();
    } // end if

    boolean isCollection = type != null ? Collection.class.isAssignableFrom(type) : false;

    if (isCollection) {

        Type rawType = type;
        if (genericType != null) {
            if (genericType instanceof ParameterizedType) {
                ParameterizedType _type = (ParameterizedType) genericType;
                Type[] actualTypeArguments = _type.getActualTypeArguments();
                rawType = actualTypeArguments[0];

            } else if (genericType instanceof GenericArrayType) {
                rawType = ((GenericArrayType) genericType).getGenericComponentType();
            }

            if (genericType instanceof WildcardType) {
                rawType = ((WildcardType) genericType).getUpperBounds()[0];
            }
        }

        if (rawType == type) {

            return new Object[] { rawType.getClass().getName() };
        } else {

            if (rawType.getClass().isAssignableFrom(TypeVariableImpl.class)) {
                return new Object[] { buildTypeStructure(
                        (Class<?>) ((ParameterizedType) oriGenericType).getActualTypeArguments()[0], rawType,
                        genericType) };
            } else {
                if (rawType instanceof ParameterizedType) {
                    if (((ParameterizedType) rawType).getRawType() == Map.class) {
                        return new Object[] { Map.class.getName() };
                    }
                }
                if (oriGenericType == rawType) {
                    return new Object[] { rawType.getClass().getName() };
                }
                return new Object[] { buildTypeStructure((Class<?>) rawType, rawType, genericType) };
            }
        }
    }

    if (type.isInterface()) {
        return type.getName();
    }

    ClassInfo paramClassInfo = RPCAPIDocletUtil.getClassInfo(type.getName());
    //added 
    if (null == paramClassInfo) {
        System.out.println("failed to get paramClassInfo for :" + type.getName());
        return null;
    }

    List<FieldInfo> typeConstructure = new ArrayList<FieldInfo>();

    BeanWrapper bean = new BeanWrapperImpl(type);

    PropertyDescriptor[] propertyDescriptors = bean.getPropertyDescriptors();
    Method readMethod;

    String name;

    for (PropertyDescriptor propertyDescriptor : propertyDescriptors) {
        readMethod = propertyDescriptor.getReadMethod();

        if (readMethod == null || "getClass".equals(readMethod.getName())) {
            continue;
        }

        name = propertyDescriptor.getName();

        FieldInfo fieldInfo = paramClassInfo.getFieldInfo(name);
        if (readMethod.getReturnType().isAssignableFrom(type)) {
            String comment = "structure is the same with parent.";
            typeConstructure
                    .add(FieldInfo.create(name, fieldInfo != null ? fieldInfo.getComment() : "", comment));
        } else {
            typeConstructure.add(
                    FieldInfo.create(name, fieldInfo != null ? fieldInfo.getComment() : "", buildTypeStructure(
                            readMethod.getReturnType(), readMethod.getGenericReturnType(), genericType)));
        } // end if
    }

    return typeConstructure;
}

From source file:gov.nih.nci.ncicb.tcga.dcc.common.jaxb.JAXBUtil.java

/**
 * Utility method for retrieving a string representation of the value referenced by a JAXB generated object.
 * <p/>/*from   w  w w  . jav  a2  s .  co  m*/
 * <p/>
 * This method assumes that <code>value</code> is a valid declared field of the object being passed to it,
 * and also contains the corresponding read method <code>getValue()</code>.
 * <p/>
 * <p/>
 * <b>This method will work with other non-JAXB generated objects that meet the requirements stated above,
 * but it is not recommended.</b>
 *
 * @param valueObject - an object that represents a JAXB generated value object
 * @return a string representation of <code>Object.getValue()</code>
 */
public static String getJAXBObjectValue(final Object valueObject) {

    String value = null;
    if (valueObject != null) {
        try {
            final Field valueField = valueObject.getClass().getDeclaredField("value");
            final PropertyDescriptor valueObjectDescriptor = new PropertyDescriptor(valueField.getName(),
                    valueObject.getClass());
            value = valueObjectDescriptor.getReadMethod().invoke(valueObject, null).toString();
        } catch (Exception e) {
            logger.error(e.getMessage());
            return value;
        }
    }

    return value;
}

From source file:com.stephenduncanjr.easymock.EasyMockPropertyUtils.java

/**
 * Gets the properties and values from the object as a map, ignoring the
 * properties specified.//  ww w.  ja va2 s  .c om
 * 
 * @param bean
 * @param ignoredProperties
 * @return map of properties names to values.
 */
private static Map<String, Object> retrieveAndFilterProperties(final Object bean,
        final List<String> ignoredProperties) {
    final Map<String, Object> map = new HashMap<String, Object>();

    try {
        for (final PropertyDescriptor p : PropertyUtils.getPropertyDescriptors(bean)) {
            if (!ignoredProperties.contains(p.getName()) && !"class".equals(p.getName())) {
                final Method readMethod = p.getReadMethod();

                if (readMethod != null) {
                    map.put(p.getName(), readMethod.invoke(bean));
                }
            }
        }
    } catch (final IllegalAccessException e) {
        throw new IllegalArgumentException(e);
    } catch (final InvocationTargetException e) {
        throw new IllegalArgumentException(e);
    }

    return map;
}

From source file:net.mojodna.searchable.util.SearchableUtils.java

/**
 * Should the specified property be stored in the index?
 * //  www. java 2s .c  o m
 * @param descriptor Property descriptor.
 * @return Whether the specified property should be stored in the index.
 */
public static final Field.Store isStored(final PropertyDescriptor descriptor) {
    for (final Class<? extends Annotation> annotationClass : Searchable.INDEXING_ANNOTATIONS) {
        final Annotation annotation = AnnotationUtils.getAnnotation(descriptor.getReadMethod(),
                annotationClass);
        if (annotation instanceof Searchable.Indexed) {
            if (((Searchable.Indexed) annotation).stored())
                return Field.Store.YES;
            else
                return Field.Store.NO;
        } else if (annotation instanceof Searchable.Stored) {
            return Field.Store.YES;
        }
    }

    return Field.Store.NO;
}

From source file:com.palantir.ptoss.util.Reflections.java

/**
 * Returns a {@link Function} that will read values from the named field from a passed object.
 * @param klass type to read values from
 * @param returnType return type of read field
 * @param getter name of the field/*from www . j  ava  2s  . c o  m*/
 * @return a {@link Function} object that, when applied to an instance of <code>klass</code>, returns the
 * of type <code>returnType</code> that resides in field <code>getter</code>
 */
public static <F, T> Function<F, T> getterFunction(final Class<F> klass, final Class<T> returnType,
        String getter) {
    try {
        BeanInfo beanInfo = Introspector.getBeanInfo(klass);
        PropertyDescriptor[] props = beanInfo.getPropertyDescriptors();
        Method method = null;
        for (PropertyDescriptor descriptor : props) {
            if (descriptor.getName().equals(getter)) {
                method = descriptor.getReadMethod();
                break;
            }
        }
        if (method == null) {
            throw new IllegalStateException();
        }
        final Method readMethod = method;
        return new Function<F, T>() {
            public T apply(F from) {
                try {
                    return returnType.cast(readMethod.invoke(from));
                } catch (Exception e) {
                    Throwables.throwUncheckedException(e);
                    return null;
                }
            }
        };
    } catch (IntrospectionException e) {
        Throwables.throwUncheckedException(e);
        return null;
    }
}