Example usage for java.beans PropertyDescriptor getName

List of usage examples for java.beans PropertyDescriptor getName

Introduction

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

Prototype

public String getName() 

Source Link

Document

Gets the programmatic name of this feature.

Usage

From source file:org.hellojavaer.testcase.generator.TestCaseGenerator.java

@SuppressWarnings({ "unchecked", "rawtypes" })
private static <T> T produceBean(Class<T> clazz, ControlParam countrolParam, Stack<Class> parseClassList) {
    try {//  w  w w .ja  v a  2 s.c  o  m
        T item = clazz.newInstance();
        for (PropertyDescriptor pd : BeanUtils.getPropertyDescriptors(clazz)) {
            Method writeMethod = pd.getWriteMethod();
            if (writeMethod == null || pd.getReadMethod() == null || //
                    countrolParam.getExcludeFieldList() != null
                            && countrolParam.getExcludeFieldList().contains(pd.getName())//
            ) {//
                continue;
            }
            Class fieldClazz = pd.getPropertyType();
            Long numIndex = countrolParam.getNumIndex();
            // int enumIndex = countrolParam.getEnumIndex();
            Random random = countrolParam.getRandom();
            long strIndex = countrolParam.getStrIndex();
            int charIndex = countrolParam.getCharIndex();
            Calendar time = countrolParam.getTime();
            if (TypeUtil.isBaseType(fieldClazz)) {
                if (TypeUtil.isNumberType(fieldClazz)) {
                    if (fieldClazz == Byte.class) {
                        writeMethod.invoke(item, Byte.valueOf((byte) (numIndex & 0x7F)));
                    } else if (fieldClazz == Short.class) {
                        writeMethod.invoke(item, Short.valueOf((short) (numIndex & 0x7FFF)));
                    } else if (fieldClazz == Integer.class) {
                        writeMethod.invoke(item, Integer.valueOf((int) (numIndex & 0x7FFFFFFF)));
                    } else if (fieldClazz == Long.class) {
                        writeMethod.invoke(item, Long.valueOf((long) numIndex));
                    } else if (fieldClazz == Float.class) {
                        writeMethod.invoke(item, Float.valueOf((float) numIndex));
                    } else if (fieldClazz == Double.class) {
                        writeMethod.invoke(item, Double.valueOf((double) numIndex));
                    } else if (fieldClazz == byte.class) {//
                        writeMethod.invoke(item, (byte) (numIndex & 0x7F));
                    } else if (fieldClazz == short.class) {
                        writeMethod.invoke(item, (short) (numIndex & 0x7FFF));
                    } else if (fieldClazz == int.class) {
                        writeMethod.invoke(item, (int) (numIndex & 0x7FFFFFFF));
                    } else if (fieldClazz == long.class) {
                        writeMethod.invoke(item, (long) numIndex);
                    } else if (fieldClazz == float.class) {
                        writeMethod.invoke(item, (float) numIndex);
                    } else if (fieldClazz == double.class) {
                        writeMethod.invoke(item, (double) numIndex);
                    }
                    numIndex++;
                    if (numIndex < 0) {
                        numIndex &= 0x7FFFFFFFFFFFFFFFL;
                    }
                    countrolParam.setNumIndex(numIndex);
                } else if (fieldClazz == boolean.class) {
                    writeMethod.invoke(item, random.nextBoolean());
                } else if (fieldClazz == Boolean.class) {
                    writeMethod.invoke(item, Boolean.valueOf(random.nextBoolean()));
                } else if (fieldClazz == char.class) {
                    writeMethod.invoke(item, CHAR_RANGE[charIndex]);
                    charIndex++;
                    if (charIndex >= CHAR_RANGE.length) {
                        charIndex = 0;
                    }
                    countrolParam.setCharIndex(charIndex);
                } else if (fieldClazz == Character.class) {
                    writeMethod.invoke(item, Character.valueOf(CHAR_RANGE[charIndex]));
                    charIndex++;
                    if (charIndex >= CHAR_RANGE.length) {
                        charIndex = 0;
                    }
                    countrolParam.setCharIndex(charIndex);
                } else if (fieldClazz == String.class) {
                    if (countrolParam.getUniqueFieldList() != null
                            && countrolParam.getUniqueFieldList().contains(pd.getName())) {
                        StringBuilder sb = new StringBuilder();
                        convertNum(strIndex, STRING_RANGE, countrolParam.getRandom(), sb);
                        writeMethod.invoke(item, sb.toString());
                        strIndex += countrolParam.getStrStep();
                        if (strIndex < 0) {
                            strIndex &= 0x7FFFFFFFFFFFFFFFL;
                        }
                        countrolParam.setStrIndex(strIndex);
                    } else {
                        writeMethod.invoke(item, String.valueOf(CHAR_RANGE[charIndex]));
                        charIndex++;
                        if (charIndex >= CHAR_RANGE.length) {
                            charIndex = 0;
                        }
                        countrolParam.setCharIndex(charIndex);
                    }

                } else if (fieldClazz == Date.class) {
                    writeMethod.invoke(item, time.getTime());
                    time.add(Calendar.DAY_OF_YEAR, 1);
                } else if (fieldClazz.isEnum()) {
                    int index = random.nextInt(fieldClazz.getEnumConstants().length);
                    writeMethod.invoke(item, fieldClazz.getEnumConstants()[index]);
                } else {
                    //
                    throw new RuntimeException("out of countrol Class " + fieldClazz.getName());
                }
            } else {
                parseClassList.push(fieldClazz);
                // TODO ?
                Set<Class> set = new HashSet<Class>(parseClassList);
                if (parseClassList.size() - set.size() <= countrolParam.getRecursiveCycleLimit()) {
                    Object bean = produceBean(fieldClazz, countrolParam, parseClassList);
                    writeMethod.invoke(item, bean);
                }
                parseClassList.pop();
            }
        }
        return item;
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}

From source file:com.unboundid.scim2.common.utils.SchemaUtils.java

/**
 * This method will find the name for the attribute, and add
 * it to the builder./*from   w w  w.j a v a2  s .  c  om*/
 *
 * @param attributeBuilder builder for a scim attribute.
 * @param propertyDescriptor property descriptor for the field to build
 *                           the attribute for.
 * @param jsonProperty the Jackson JsonProperty annotation for the field.
 * @return this.
 */
private static AttributeDefinition.Builder addName(final AttributeDefinition.Builder attributeBuilder,
        final PropertyDescriptor propertyDescriptor, final JsonProperty jsonProperty) {
    if (jsonProperty != null && !jsonProperty.value().equals(JsonProperty.USE_DEFAULT_NAME)) {
        attributeBuilder.setName(jsonProperty.value());
    } else {
        attributeBuilder.setName(propertyDescriptor.getName());
    }

    return attributeBuilder;
}

From source file:ch.flashcard.HibernateDetachUtility.java

private static void nullOutFieldsByAccessors(Object value, Map<Integer, Object> checkedObjects,
        Map<Integer, List<Object>> checkedObjectCollisionMap, int depth, SerializationType serializationType)
        throws Exception {
    // Null out any collections that aren't loaded
    BeanInfo bi = Introspector.getBeanInfo(value.getClass(), Object.class);

    PropertyDescriptor[] pds = bi.getPropertyDescriptors();
    for (PropertyDescriptor pd : pds) {
        Object propertyValue = null;
        try {// www  .  j a v  a 2s  .  c  o m
            propertyValue = pd.getReadMethod().invoke(value);
        } catch (Throwable lie) {
            if (LOG.isDebugEnabled()) {
                LOG.debug("Couldn't load: " + pd.getName() + " off of " + value.getClass().getSimpleName(),
                        lie);
            }
        }

        if (!Hibernate.isInitialized(propertyValue)) {
            try {
                if (LOG.isDebugEnabled()) {
                    LOG.debug("Nulling out: " + pd.getName() + " off of " + value.getClass().getSimpleName());
                }

                Method writeMethod = pd.getWriteMethod();
                if ((writeMethod != null) && (writeMethod.getAnnotation(XmlTransient.class) == null)) {
                    pd.getWriteMethod().invoke(value, new Object[] { null });
                } else {
                    nullOutField(value, pd.getName());
                }
            } catch (Exception lie) {
                LOG.debug("Couldn't null out: " + pd.getName() + " off of " + value.getClass().getSimpleName()
                        + " trying field access", lie);
                nullOutField(value, pd.getName());
            }
        } else {
            if ((propertyValue instanceof Collection) || ((propertyValue != null)
                    && propertyValue.getClass().getName().startsWith("org.rhq.core.domain"))) {
                nullOutUninitializedFields(propertyValue, checkedObjects, checkedObjectCollisionMap, depth + 1,
                        serializationType);
            }
        }
    }
}

From source file:gr.interamerican.bo2.utils.JavaBeanUtils.java

/**
 * Gets the value of a property on an object.
 * /*from ww  w.j  a v  a  2  s. c o m*/
 * If the property has a getter method, then it will be called.
 * If the property does not have a getter method, the field
 * will be get. If there is no such field, then a RuntimeException
 * with cause a NoSuchFieldException will be thrown. <br/>
 * The method will box any {@link Exception} thrown during java reflection
 * calls inside a {@link RuntimeException}.
 * 
 * @param pd
 *            Descriptor of the property.
 * @param obj
 *            Object on which the property is accessed.
 *            
 * @return Returns the value of this property.
 */
public static Object getProperty(PropertyDescriptor pd, Object obj) {
    Method getter = pd.getReadMethod();
    if (getter != null) {
        return ReflectionUtils.invoke(getter, obj);
    } else {
        String fieldName = pd.getName();
        try {
            Field field = obj.getClass().getDeclaredField(fieldName);
            field.setAccessible(true);
            return ReflectionUtils.get(field, obj);
        } catch (NoSuchFieldException nse) {
            throw new RuntimeException(nse);
        }
    }
}

From source file:disko.DU.java

@SuppressWarnings("unchecked")
public static <T> T cloneObject(T p, Mapping<Pair<Object, String>, Boolean> propertyFilter) throws Exception {
    if (p == null)
        return null;

    if (p instanceof Cloneable) {
        Method cloneMethod = p.getClass().getMethod("clone", (Class[]) null);
        if (cloneMethod != null)
            return (T) cloneMethod.invoke(p, (Object[]) null);

    } else if (p.getClass().isArray()) {
        Object[] A = (Object[]) p;
        Class<?> type = p.getClass();
        Object[] ac = (Object[]) Array.newInstance(type.getComponentType(), A.length);
        for (int i = 0; i < A.length; i++)
            ac[i] = cloneObject(A[i], propertyFilter);
        return (T) ac;
    } else if (identityCloneClasses.contains(p.getClass()))
        return p;

    ///*from  w w  w . jav  a 2 s  .  c om*/
    // Need to implement cloning ourselves. We do this by copying bean properties.
    //
    Constructor<?> cons = null;

    try {
        cons = p.getClass().getConstructor((Class[]) null);
    } catch (Throwable t) {
        return p;
    }

    Object copy = cons.newInstance((Object[]) null);

    if (p instanceof Collection) {
        Collection<Object> cc = (Collection<Object>) copy;
        for (Object el : (Collection<?>) p)
            cc.add(cloneObject(el, propertyFilter));
    } else if (p instanceof Map) {
        Map<Object, Object> cm = (Map<Object, Object>) copy;
        for (Object key : ((Map<Object, Object>) p).keySet())
            cm.put(key, cloneObject(((Map<Object, Object>) p).get(key), propertyFilter));
    } else {
        BeanInfo bean_info = Introspector.getBeanInfo(p.getClass());
        PropertyDescriptor beanprops[] = bean_info.getPropertyDescriptors();
        if (beanprops == null || beanprops.length == 0)
            copy = p;
        else
            for (PropertyDescriptor desc : beanprops) {
                Method rm = desc.getReadMethod();
                Method wm = desc.getWriteMethod();
                if (rm == null || wm == null)
                    continue;
                Object value = rm.invoke(p, (Object[]) null);
                if (propertyFilter == null || propertyFilter.eval(new Pair<Object, String>(p, desc.getName())))
                    value = cloneObject(value, propertyFilter);
                wm.invoke(copy, new Object[] { value });
            }
    }
    return (T) copy;
}

From source file:gr.interamerican.bo2.utils.JavaBeanUtils.java

/**
 * Sets the value of a property on an object.
 * //from w  w  w .  ja v a 2s.co  m
 * If the property has a setter method, then it will be called.
 * If the property does not have a setter method, the field
 * will be set. If there is no such field, then the method will
 * ignore it. <br/>
 * The method will box any {@link Exception} thrown during java reflection
 * calls inside a {@link RuntimeException}.
 * 
 * @param pd
 *            Descriptor of the property.
 * @param val
 *            New value for the field.
 * @param obj
 *            Object on which the field value is changed.
 */
static void setPropertyTyped(PropertyDescriptor pd, Object val, Object obj) {
    Method setter = pd.getWriteMethod();
    if (setter != null) {
        Object[] args = { val };
        ReflectionUtils.invoke(setter, obj, args);
    } else {
        String fieldName = pd.getName();
        try {
            Field field = obj.getClass().getDeclaredField(fieldName);
            field.setAccessible(true);
            ReflectionUtils.set(field, val, obj);
        } catch (NoSuchFieldException nse) {
            throw new RuntimeException(nse);
        }
    }
}

From source file:es.caib.zkib.jxpath.util.ValueUtils.java

/**
 * Returns the value of the bean's property represented by
 * the supplied property descriptor.// www . j  a  v a  2s . c om
 * @param bean to read
 * @param propertyDescriptor indicating what to read
 * @return Object value
 */
public static Object getValue(Object bean, PropertyDescriptor propertyDescriptor) {
    Object value;
    try {
        Method method = getAccessibleMethod(propertyDescriptor.getReadMethod());
        if (method == null) {
            throw new JXPathException("No read method");
        }
        value = method.invoke(bean, new Object[0]);
    } catch (Exception ex) {
        throw new JXPathException("Cannot access property: "
                + (bean == null ? "null" : bean.getClass().getName()) + "." + propertyDescriptor.getName(), ex);
    }
    return value;
}

From source file:com.trigonic.utils.spring.cmdline.OptionPropertyHandler.java

public OptionPropertyHandler(Option option, PropertyDescriptor property, Class<?> beanClass) {
    super(option, property.getName(),
            BeanUtils.findPropertyType(property.getName(), new Class[] { beanClass }));
}

From source file:com.swingtech.commons.util.ClassUtil.java

public static Class getPropertyType(final Class clazz, final String propertyName) {
    PropertyDescriptor[] propertyDescriptorList = null;
    PropertyDescriptor propertyDescriptor = null;

    if (clazz == null) {
        throw new IllegalArgumentException("clazz is null");
    }//from  w  w w.j a  v a2s  . c  o  m

    if (propertyName == null) {
        throw new IllegalArgumentException("propertyName is null");
    }

    propertyDescriptorList = PropertyUtils.getPropertyDescriptors(clazz);

    for (int i = 0; i < propertyDescriptorList.length; i++) {
        propertyDescriptor = propertyDescriptorList[i];

        if (propertyDescriptor.getName().equalsIgnoreCase(propertyName)) {
            return propertyDescriptor.getPropertyType();
        }
    }

    return null;
}

From source file:com.trigonic.utils.spring.cmdline.OperandPropertyHandler.java

public OperandPropertyHandler(Operand operand, PropertyDescriptor property, Class<?> beanClass) {
    super(operand, property.getName(),
            BeanUtils.findPropertyType(property.getName(), new Class[] { beanClass }));
}