Example usage for java.beans PropertyDescriptor getPropertyType

List of usage examples for java.beans PropertyDescriptor getPropertyType

Introduction

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

Prototype

public synchronized Class<?> getPropertyType() 

Source Link

Document

Returns the Java type info for the property.

Usage

From source file:org.apache.syncope.core.misc.jexl.JexlUtil.java

public static JexlContext addFieldsToContext(final Object object, final JexlContext jexlContext) {
    JexlContext context = jexlContext == null ? new MapContext() : jexlContext;

    try {// w w w .  j  a v a  2s.c o m
        for (PropertyDescriptor desc : Introspector.getBeanInfo(object.getClass()).getPropertyDescriptors()) {
            final Class<?> type = desc.getPropertyType();
            final String fieldName = desc.getName();

            if ((!fieldName.startsWith("pc")) && (!ArrayUtils.contains(IGNORE_FIELDS, fieldName))
                    && (!Iterable.class.isAssignableFrom(type)) && (!type.isArray())) {
                try {
                    final Method getter = desc.getReadMethod();

                    final Object fieldValue;

                    if (getter == null) {
                        final Field field = object.getClass().getDeclaredField(fieldName);
                        field.setAccessible(true);
                        fieldValue = field.get(object);
                    } else {
                        fieldValue = getter.invoke(object);
                    }

                    context.set(fieldName,
                            fieldValue == null ? StringUtils.EMPTY
                                    : (type.equals(Date.class) ? DataFormat.format((Date) fieldValue, false)
                                            : fieldValue));

                    LOG.debug("Add field {} with value {}", fieldName, fieldValue);

                } catch (Exception iae) {
                    LOG.error("Reading '{}' value error", fieldName, iae);
                }
            }
        }
    } catch (IntrospectionException ie) {
        LOG.error("Reading class attributes error", ie);
    }

    return context;
}

From source file:com.glaf.core.util.Tools.java

public static Map<String, Class<?>> getPropertyMap(Class<?> clazz) {
    Map<String, Class<?>> dataMap = new java.util.HashMap<String, Class<?>>();
    PropertyDescriptor[] propertyDescriptor = BeanUtils.getPropertyDescriptors(clazz);
    for (int i = 0; i < propertyDescriptor.length; i++) {
        PropertyDescriptor descriptor = propertyDescriptor[i];
        String propertyName = descriptor.getName();
        if (propertyName.equalsIgnoreCase("class")) {
            continue;
        }//w w  w  . j a v a2  s . c  o m
        dataMap.put(propertyName, descriptor.getPropertyType());
    }
    return dataMap;
}

From source file:org.apache.syncope.core.util.jexl.JexlUtil.java

public static JexlContext addFieldsToContext(final Object attributable, final JexlContext jexlContext) {
    JexlContext context = jexlContext == null ? new MapContext() : jexlContext;

    try {/* w w  w. j a  v  a  2  s. c o m*/
        for (PropertyDescriptor desc : Introspector.getBeanInfo(attributable.getClass())
                .getPropertyDescriptors()) {
            final Class<?> type = desc.getPropertyType();
            final String fieldName = desc.getName();

            if ((!fieldName.startsWith("pc")) && (!ArrayUtils.contains(IGNORE_FIELDS, fieldName))
                    && (!Iterable.class.isAssignableFrom(type)) && (!type.isArray())) {
                try {
                    final Method getter = desc.getReadMethod();

                    final Object fieldValue;

                    if (getter == null) {
                        final Field field = attributable.getClass().getDeclaredField(fieldName);
                        field.setAccessible(true);
                        fieldValue = field.get(attributable);
                    } else {
                        fieldValue = getter.invoke(attributable);
                    }

                    context.set(fieldName,
                            fieldValue == null ? ""
                                    : (type.equals(Date.class) ? DataFormat.format((Date) fieldValue, false)
                                            : fieldValue));

                    LOG.debug("Add field {} with value {}", fieldName, fieldValue);

                } catch (Exception iae) {
                    LOG.error("Reading '{}' value error", fieldName, iae);
                }
            }
        }
    } catch (IntrospectionException ie) {
        LOG.error("Reading class attributes error", ie);
    }

    return context;
}

From source file:com.sparkplatform.api.core.PropertyAsserter.java

/**
 * See {@link #assertBasicGetterSetterBehavior(Object,String)} method. Only difference is that here we accept an
 * explicit argument for the setter method.
 *
 * @param target   the object on which to invoke the getter and setter
 * @param property the property name, e.g. "firstName"
 * @param argument the property value, i.e. the value the setter will be invoked with
 *//*from ww  w. ja va 2  s . c  om*/
public static void assertBasicGetterSetterBehavior(Object target, String property, Object argument) {
    try {
        PropertyDescriptor descriptor = new PropertyDescriptor(property, target.getClass());
        Object arg = argument;
        Class type = descriptor.getPropertyType();
        if (arg == null) {
            if (type.isArray()) {
                arg = Array.newInstance(type.getComponentType(), new int[] { TEST_ARRAY_SIZE });
            } else if (type.isEnum()) {
                arg = type.getEnumConstants()[0];
            } else if (TYPE_ARGUMENTS.containsKey(type)) {
                arg = TYPE_ARGUMENTS.get(type);
            } else {
                arg = invokeDefaultConstructorEvenIfPrivate(type);
            }
        }

        Method writeMethod = descriptor.getWriteMethod();
        Method readMethod = descriptor.getReadMethod();

        writeMethod.invoke(target, arg);
        Object propertyValue = readMethod.invoke(target);
        if (type.isPrimitive()) {
            assertEquals(property + " getter/setter failed test", arg, propertyValue);
        } else {
            assertSame(property + " getter/setter failed test", arg, propertyValue);
        }
    } catch (IntrospectionException e) {
        String msg = "Error creating PropertyDescriptor for property [" + property
                + "]. Do you have a getter and a setter?";
        log.error(msg, e);
        fail(msg);
    } catch (IllegalAccessException e) {
        String msg = "Error accessing property. Are the getter and setter both accessible?";
        log.error(msg, e);
        fail(msg);
    } catch (InvocationTargetException e) {
        String msg = "Error invoking method on target";
        log.error(msg, e);
        fail(msg);
    }
}

From source file:com.ksmpartners.ernie.util.TestUtil.java

/**
 * Performs the getter/setter tests on the java object. The method works by
 * iterating over the declared fields (ignoring static fields) and ensures
 * that each field has a getter and setter (as indicated by the parameters)
 * and that the results of calling the setter followed by the getter match.
 * <p>/*from w  ww.j  a v a2  s  .c  o  m*/
 */
public static void populateFields(Class clazz, Object target) {

    PropertyDescriptor[] properties = PropertyUtils.getPropertyDescriptors(target);
    for (PropertyDescriptor property : properties) {

        final String qName = "[" + clazz.getName() + "]." + property.getName();
        final Class<?> fieldType = property.getPropertyType();

        // ignore getClass() and isEmpty()
        if (property.getName().equals("class") || property.getName().equals("empty"))
            continue;

        // create a test value for our setter
        Object setValue = createSetValue(qName, fieldType);
        testProperty(target, property, setValue, qName);
    }
}

From source file:org.jaxygen.typeconverter.util.BeanUtil.java

/**
 * Copies bean content from one bean to another. The bean is copied using the
 * set and get methods. Method invokes all getXX methods on the from object,
 * and result pass to the corresponding setXX methods in the to object. Note
 * that it is not obvious that both object are of the same type.
 * If get and set methods do not match then it tries to use appropriate
 * converter registered in default type converter factory.
 *
 * @param from data provider object.//w ww  .  j  a va  2  s .  co m
 * @param to data acceptor object.
 */
public static void translateBean(Object from, Object to) {
    PropertyDescriptor[] fromGetters = null;
    fromGetters = PropertyUtils.getPropertyDescriptors(from.getClass());
    for (PropertyDescriptor pd : fromGetters) {
        if (pd.getReadMethod().isAnnotationPresent(BeanTransient.class) == false) {
            if (PropertyUtils.isWriteable(to, pd.getName())) {
                try {
                    PropertyDescriptor wd = PropertyUtils.getPropertyDescriptor(to, pd.getName());
                    if (!wd.getWriteMethod().isAnnotationPresent(BeanTransient.class)) {
                        Object copyVal = PropertyUtils.getProperty(from, pd.getName());
                        if (wd.getPropertyType().isAssignableFrom(pd.getPropertyType())) {
                            PropertyUtils.setProperty(to, wd.getName(), copyVal);
                        } else {
                            try {
                                Object convertedCopyVal = TypeConverterFactory.instance().convert(copyVal,
                                        wd.getPropertyType());
                                PropertyUtils.setProperty(to, wd.getName(), convertedCopyVal);
                            } catch (ConversionError ex) {
                                Logger.getAnonymousLogger().log(Level.WARNING,
                                        "Method {0}.{1} of type {2} is not compatible to {3}.{4} of type{5}",
                                        new Object[] { from.getClass().getName(), pd.getName(),
                                                pd.getPropertyType(), to.getClass().getName(), wd.getName(),
                                                wd.getPropertyType() });
                            }
                        }
                    }
                } catch (IllegalAccessException ex) {
                    throw new java.lang.IllegalArgumentException("Could not translate bean", ex);
                } catch (InvocationTargetException ex) {
                    throw new java.lang.IllegalArgumentException("Could not translate bean", ex);
                } catch (NoSuchMethodException ex) {
                    throw new java.lang.IllegalArgumentException("Could not translate bean", ex);
                }
            }
        }
    }
}

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

/**
 * Doesn't work yet!//from   w  w  w .j  a  v a  2s .co m
 *
 * @param bean
 */
public static void cleanBean(Object bean) {
    if (bean == null)
        return;

    try {
        BeanInfo bi = Introspector.getBeanInfo(bean.getClass());
        PropertyDescriptor pds[] = bi.getPropertyDescriptors();
        PropertyDescriptor pd = null;
        for (int i = 0; i < pds.length; i++) {
            pd = pds[i];
            //Method getter = pd.getReadMethod();
            Method setter = pd.getWriteMethod();
            if (pd.getPropertyType() == Integer.class) {
                setter.invoke(bean, new Object[] { new Integer(0) });
            } else if (pd.getPropertyType() == Double.class) {
                setter.invoke(bean, new Object[] { new Double(0) });
            } else {
                try {
                    setter.invoke(bean, new Object[] { null });
                } catch (Throwable e) {
                    log.warn("cleanBean()", e);
                }
            }
        }
    } catch (Throwable e) {
        log.warn("cleanBean()", e);
    }
}

From source file:org.jspresso.framework.util.bean.PropertyHelper.java

private static PropertyDescriptor getPropertyDescriptorNoException(Class<?> beanClass, String property) {
    PropertyDescriptor descriptorToReturn = null;
    int nestedDotIndex = property.indexOf(IAccessor.NESTED_DELIM);
    if (nestedDotIndex > 0) {
        PropertyDescriptor rootDescriptor = getPropertyDescriptorNoException(beanClass,
                property.substring(0, nestedDotIndex));
        if (rootDescriptor != null) {
            descriptorToReturn = getPropertyDescriptorNoException(rootDescriptor.getPropertyType(),
                    property.substring(nestedDotIndex + 1));
        }/*from  w w  w. j a v  a 2s .  c o m*/
    } else {
        PropertyDescriptor[] descriptors = PropertyUtils.getPropertyDescriptors(beanClass);
        for (PropertyDescriptor descriptor : descriptors) {
            if (property.substring(0, 1).equalsIgnoreCase(descriptor.getName().substring(0, 1))
                    && property.substring(1).equals(descriptor.getName().substring(1))) {
                // 1st letter might be uppercase in descriptor and lowercase in
                // property when property name is like 'tEst'.
                descriptorToReturn = descriptor;
            }
        }
    }
    if (descriptorToReturn == null || descriptorToReturn.getWriteMethod() == null) {
        // If we reach this point, no property with the given name has been found.
        // or the found descriptor is read-only.
        // If beanClass is indeed an interface, we must also deal with all its
        // super-interfaces.
        List<Class<?>> superTypes = new ArrayList<>();
        if (beanClass.getSuperclass() != null && beanClass.getSuperclass() != Object.class) {
            superTypes.add(beanClass.getSuperclass());
        }
        Collections.addAll(superTypes, beanClass.getInterfaces());
        for (Class<?> superType : superTypes) {
            PropertyDescriptor descriptor;
            descriptor = getPropertyDescriptorNoException(superType, property);
            if (descriptor != null) {
                if (descriptorToReturn != null) {
                    try {
                        descriptorToReturn.setWriteMethod(descriptor.getWriteMethod());
                    } catch (IntrospectionException ex) {
                        throw new NestedRuntimeException(ex);
                    }
                } else {
                    descriptorToReturn = descriptor;
                }
            }
        }
    }
    return descriptorToReturn;
}

From source file:com.mycomm.dao.mydao.base.MyDaoSupport.java

/**
 * ?,hibernate???select count(o) from Xxx
 * o?BUG,hibernatejpql??sqlselect//w  w  w . ja  v a 2s .co m
 * count(field1,field2,...),count()
 *
 * @param <E>
 * @param clazz
 * @return
 */
protected static <E> String getCountField(Class<E> clazz) {
    String out = "o";
    try {
        PropertyDescriptor[] propertyDescriptors = Introspector.getBeanInfo(clazz).getPropertyDescriptors();
        for (PropertyDescriptor propertydesc : propertyDescriptors) {
            Method method = propertydesc.getReadMethod();
            if (method != null && method.isAnnotationPresent(EmbeddedId.class)) {
                PropertyDescriptor[] ps = Introspector.getBeanInfo(propertydesc.getPropertyType())
                        .getPropertyDescriptors();
                out = "o." + propertydesc.getName() + "."
                        + (!ps[1].getName().equals("class") ? ps[1].getName() : ps[0].getName());
                break;
            }
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
    return out;
}

From source file:org.eclipse.wb.internal.swing.databinding.model.generic.GenericUtils.java

public static IGenericType getObjectType(TypeVariable<?> superTypeParameter, Type superTypeParameterClass,
        PropertyDescriptor descriptor) {
    Method readMethod = descriptor.getReadMethod();
    Class<?> rawType = descriptor.getPropertyType();
    if (readMethod == null) {
        return new ClassGenericType(rawType, null, null);
    }//from  ww  w . j a  v  a 2  s . c o m
    Type type = readMethod.getGenericReturnType();
    if (type instanceof Class<?> || type instanceof TypeVariable<?>) {
        return new ClassGenericType(rawType, null, null);
    }
    if (type instanceof ParameterizedType) {
        GenericTypeContainer genericType = new GenericTypeContainer(rawType);
        ParameterizedType parameterizedType = (ParameterizedType) type;
        //
        if (superTypeParameter != null && parameterizedType.getActualTypeArguments().length == 1
                && superTypeParameter == parameterizedType.getActualTypeArguments()[0]) {
            genericType.getSubTypes().add(resolveType(superTypeParameterClass));
            return genericType;
        }
        for (Type subType : parameterizedType.getActualTypeArguments()) {
            genericType.getSubTypes().add(resolveType(subType));
        }
        return genericType;
    }
    if (type instanceof GenericArrayType) {
        int dimension = 0;
        Type elementType = null;
        GenericArrayType arrayType = (GenericArrayType) type;
        while (true) {
            dimension++;
            elementType = arrayType.getGenericComponentType();
            if (elementType instanceof GenericArrayType) {
                arrayType = (GenericArrayType) elementType;
                continue;
            }
            break;
        }
        GenericTypeContainer genericType = new GenericTypeContainer(rawType, dimension);
        genericType.getSubTypes().add(resolveType(elementType));
        return genericType;
    }
    Assert.fail(MessageFormat.format("Undefine type: {0} {1}", readMethod, rawType));
    return null;
}