Java Code Examples for java.beans.PropertyDescriptor#getPropertyType()

The following examples show how to use java.beans.PropertyDescriptor#getPropertyType() . These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
/**
 * Return the Class of the property if it can be determined.
 * @param bean The bean containing the property.
 * @param propName The name of the property.
 * @return The class associated with the property or null.
 */
private static Class<?> getDefaultClass(final Object bean, final String propName)
{
    try
    {
        final PropertyDescriptor desc =
                BEAN_UTILS_BEAN.getPropertyUtils().getPropertyDescriptor(
                        bean, propName);
        if (desc == null)
        {
            return null;
        }
        return desc.getPropertyType();
    }
    catch (final Exception ex)
    {
        return null;
    }
}
 
Example 2
/**
 * Validates a primitive in a BO
 *
 * @param entryName
 * @param object
 * @param propertyDescriptor
 * @param errorPrefix
 * @param validateRequired
 */
protected void validatePrimitiveFromDescriptor(String entryName, Object object, PropertyDescriptor propertyDescriptor, String errorPrefix, boolean validateRequired) {

    // validate the primitive attributes if defined in the dictionary
    if (null != propertyDescriptor && dataDictionaryService.isAttributeDefined(entryName, propertyDescriptor.getName())) {
        Object value = ObjectUtils.getPropertyValue(object, propertyDescriptor.getName());
        Class propertyType = propertyDescriptor.getPropertyType();

        if (TypeUtils.isStringClass(propertyType) || TypeUtils.isIntegralClass(propertyType) || TypeUtils.isDecimalClass(propertyType) || TypeUtils.isTemporalClass(propertyType)) {

            // check value format against dictionary
            if (value != null && StringUtils.isNotBlank(value.toString())) {
                if (!TypeUtils.isTemporalClass(propertyType)) {
                    SpringContext.getBean(DictionaryValidationService.class).validate( object, entryName, propertyDescriptor.getName(), false);
                }
            } else if (validateRequired) {
                SpringContext.getBean(DictionaryValidationService.class).validate( object, entryName, propertyDescriptor.getName(), true);
            }
        }
    }
}
 
Example 3
public Collection<Class<?>> extractDataClasses(Collection<Class<?>> input, String targetDirectory) {

        Set<Class<?>> dataModelClasses = new HashSet<>();
        for (Class<?> modelClazz : input) {
            try {
                BeanInfo beanInfo = Introspector.getBeanInfo(modelClazz);
                for (PropertyDescriptor pd : beanInfo.getPropertyDescriptors()) {
                    Class<?> propertyType = pd.getPropertyType();
                    if (propertyType.getCanonicalName().startsWith("java.lang") 
                            || propertyType.getCanonicalName().equals(Date.class.getCanonicalName())) {
                        continue;
                    }

                    dataModelClasses.add(propertyType);
                }

                generateModelClassProto(modelClazz, targetDirectory);
            } catch (Exception e) {
                throw new RuntimeException(e);
            }
        }

        return dataModelClasses;
    }
 
Example 4
public void run() {
    for (String name : this.names) {
        Object bean;
        try {
            bean = this.loader.loadClass(name).newInstance();
        } catch (Exception exception) {
            throw new Error("could not instantiate bean: " + name, exception);
        }
        if (this.loader != bean.getClass().getClassLoader()) {
            throw new Error("bean class loader is not equal to default one");
        }
        PropertyDescriptor[] pds = getPropertyDescriptors(bean);
        for (PropertyDescriptor pd : pds) {
            Class type = pd.getPropertyType();
            Method setter = pd.getWriteMethod();
            Method getter = pd.getReadMethod();

            if (type.equals(String.class)) {
                executeMethod(setter, bean, "Foo");
            } else if (type.equals(int.class)) {
                executeMethod(setter, bean, Integer.valueOf(1));
            }
            executeMethod(getter, bean);
        }
    }
}
 
Example 5
/**
 * @see org.kuali.kfs.module.cam.document.service.AssetPaymentService#adjustPaymentAmounts(org.kuali.kfs.module.cam.businessobject.AssetPayment,
 *      boolean, boolean)
 */
public void adjustPaymentAmounts(AssetPayment assetPayment, boolean reverseAmount, boolean nullPeriodDepreciation) throws IllegalAccessException, InvocationTargetException {
    LOG.debug("Starting - adjustAmounts() ");
    PropertyDescriptor[] propertyDescriptors = PropertyUtils.getPropertyDescriptors(AssetPayment.class);
    for (PropertyDescriptor propertyDescriptor : propertyDescriptors) {
        Method readMethod = propertyDescriptor.getReadMethod();
        if (readMethod != null && propertyDescriptor.getPropertyType() != null && KualiDecimal.class.isAssignableFrom(propertyDescriptor.getPropertyType())) {
            KualiDecimal amount = (KualiDecimal) readMethod.invoke(assetPayment);
            Method writeMethod = propertyDescriptor.getWriteMethod();
            if (writeMethod != null && amount != null) {
                // Reset periodic depreciation expenses
                if (nullPeriodDepreciation && Pattern.matches(CamsConstants.SET_PERIOD_DEPRECIATION_AMOUNT_REGEX, writeMethod.getName().toLowerCase())) {
                    Object[] nullVal = new Object[] { null };
                    writeMethod.invoke(assetPayment, nullVal);
                }
                else if (reverseAmount) {
                    // reverse the amounts
                    writeMethod.invoke(assetPayment, (amount.negated()));
                }
            }

        }
    }
    LOG.debug("Finished - adjustAmounts()");
}
 
Example 6
Source Project: hottub   File: Test8027905.java    License: GNU General Public License v2.0 6 votes vote down vote up
public static void main(String[] args) {
    PropertyDescriptor pd = BeanUtils.getPropertyDescriptor(Sub.class, "foo");
    Class<?> type = pd.getPropertyType();

    int[] array = new int[10];
    while (array != null) {
        try {
            array = new int[array.length + array.length];
        }
        catch (OutOfMemoryError error) {
            array = null;
        }
    }
    if (type != pd.getPropertyType()) {
        throw new Error("property type is changed");
    }
}
 
Example 7
Source Project: blog_demos   File: ExtendedBeanInfo.java    License: Apache License 2.0 6 votes vote down vote up
private PropertyDescriptor findExistingPropertyDescriptor(String propertyName, Class<?> propertyType) {
	for (PropertyDescriptor pd : this.propertyDescriptors) {
		final Class<?> candidateType;
		final String candidateName = pd.getName();
		if (pd instanceof IndexedPropertyDescriptor) {
			IndexedPropertyDescriptor ipd = (IndexedPropertyDescriptor) pd;
			candidateType = ipd.getIndexedPropertyType();
			if (candidateName.equals(propertyName) &&
					(candidateType.equals(propertyType) || candidateType.equals(propertyType.getComponentType()))) {
				return pd;
			}
		}
		else {
			candidateType = pd.getPropertyType();
			if (candidateName.equals(propertyName) &&
					(candidateType.equals(propertyType) || propertyType.equals(candidateType.getComponentType()))) {
				return pd;
			}
		}
	}
	return null;
}
 
Example 8
Source Project: java-technology-stack   File: BeanUtils.java    License: MIT License 5 votes vote down vote up
/**
 * Determine the bean property type for the given property from the
 * given classes/interfaces, if possible.
 * @param propertyName the name of the bean property
 * @param beanClasses the classes to check against
 * @return the property type, or {@code Object.class} as fallback
 */
public static Class<?> findPropertyType(String propertyName, @Nullable Class<?>... beanClasses) {
	if (beanClasses != null) {
		for (Class<?> beanClass : beanClasses) {
			PropertyDescriptor pd = getPropertyDescriptor(beanClass, propertyName);
			if (pd != null) {
				return pd.getPropertyType();
			}
		}
	}
	return Object.class;
}
 
Example 9
Source Project: jeesuite-libs   File: BeanUtils.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * 把对象值为0的包装类型属性转为null
 *
 * @param bean
 * @param excludeFields 排除不处理的字段
 * @throws BeanConverterException
 */
public static void zeroWrapPropertiesToNull(Object bean, String... excludeFields) throws BeanConverterException {
    try {
        Map<String, PropertyDescriptor> srcDescriptors = getCachePropertyDescriptors(bean.getClass());
        Set<String> keys = srcDescriptors.keySet();

        List<String> excludeFieldsList = null;
        if (excludeFields != null && excludeFields.length > 0 && StringUtils.isNotBlank(excludeFields[0])) {
            excludeFieldsList = Arrays.asList(excludeFields);
        }

        for (String key : keys) {
            PropertyDescriptor srcDescriptor = srcDescriptors.get(key);
            if (srcDescriptor == null) continue;
            if (excludeFieldsList != null && excludeFieldsList.contains(key)) continue;
            Object value = srcDescriptor.getReadMethod().invoke(bean);

            boolean isWrapType = srcDescriptor.getPropertyType() == Long.class || srcDescriptor.getPropertyType() == Integer.class || srcDescriptor.getPropertyType() == Short.class || srcDescriptor.getPropertyType() == Double.class || srcDescriptor.getPropertyType() == Float.class;
            if (isWrapType && value != null && Integer.parseInt(value.toString()) == 0) {
                value = null;
                Method writeMethod = srcDescriptor.getWriteMethod();
                if (writeMethod != null) writeMethod.invoke(bean, value);
            }

        }
    } catch (Exception e) {
        throw new BeanConverterException(e);
    }
}
 
Example 10
private static Class<?> getPropertyType(Class<?> type, boolean indexed) {
    PropertyDescriptor pd = BeanUtils.findPropertyDescriptor(type, indexed ? "index" : "value");
    if (pd instanceof IndexedPropertyDescriptor) {
        IndexedPropertyDescriptor ipd = (IndexedPropertyDescriptor) pd;
        return ipd.getIndexedPropertyType();
    }
    return pd.getPropertyType();
}
 
Example 11
Source Project: spring4-understanding   File: BeanUtils.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Determine the bean property type for the given property from the
 * given classes/interfaces, if possible.
 * @param propertyName the name of the bean property
 * @param beanClasses the classes to check against
 * @return the property type, or {@code Object.class} as fallback
 */
public static Class<?> findPropertyType(String propertyName, Class<?>... beanClasses) {
	if (beanClasses != null) {
		for (Class<?> beanClass : beanClasses) {
			PropertyDescriptor pd = getPropertyDescriptor(beanClass, propertyName);
			if (pd != null) {
				return pd.getPropertyType();
			}
		}
	}
	return Object.class;
}
 
Example 12
private static Class<?> getPropertyType(Class<?> type, boolean indexed) {
    PropertyDescriptor pd = BeanUtils.findPropertyDescriptor(type, indexed ? "index" : "value");
    if (pd instanceof IndexedPropertyDescriptor) {
        IndexedPropertyDescriptor ipd = (IndexedPropertyDescriptor) pd;
        return ipd.getIndexedPropertyType();
    }
    return pd.getPropertyType();
}
 
Example 13
Source Project: anno4j   File: PropertyMapper.java    License: Apache License 2.0 5 votes vote down vote up
private void findFunctionalProperties(Class<?> concept,
		Map<String, PropertyDescriptor> properties) {
	for (PropertyDescriptor pd : findProperties(concept)) {
		Class<?> type = pd.getPropertyType();
		if (Set.class.equals(type))
			continue;
		properties.put(pd.getName(), pd);
	}
	for (Class<?> face : concept.getInterfaces()) {
		findFunctionalProperties(face, properties);
	}
	if (concept.getSuperclass() != null)
		findFunctionalProperties(concept.getSuperclass(), properties);
}
 
Example 14
Source Project: cia   File: FormFactoryImpl.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Gets the type of property.
 *
 * @param propertyDescriptors
 *            the property descriptors
 * @param property
 *            the property
 * @return the type of property
 */
private static Class<?> getTypeOfProperty(final PropertyDescriptor[] propertyDescriptors, final String property) {

	for (final PropertyDescriptor propertyDescriptor : propertyDescriptors) {
		if (propertyDescriptor.getName().equalsIgnoreCase(property)) {
			return propertyDescriptor.getPropertyType();
		}
	}
	return null;
}
 
Example 15
private static boolean compare(PropertyDescriptor pd1, PropertyDescriptor pd2) {
    if (!compare(pd1.getReadMethod(), pd2.getReadMethod())) {
        System.out.println("read methods not equal");
        return false;
    }
    if (!compare(pd1.getWriteMethod(), pd2.getWriteMethod())) {
        System.out.println("write methods not equal");
        return false;
    }
    if (pd1.getPropertyType() != pd2.getPropertyType()) {
        System.out.println("property type not equal");
        return false;
    }
    if (pd1.getPropertyEditorClass() != pd2.getPropertyEditorClass()) {
        System.out.println("property editor class not equal");
        return false;
    }
    if (pd1.isBound() != pd2.isBound()) {
        System.out.println("bound value not equal");
        return false;
    }
    if (pd1.isConstrained() != pd2.isConstrained()) {
        System.out.println("constrained value not equal");
        return false;
    }
    return true;
}
 
Example 16
/**
 * Utility method which can compute the difference between source amount and consumed amounts, then will adjust the last amount
 * 
 * @param source Source payments
 * @param consumedList Consumed Payments
 */
private void applyBalanceToPaymentAmounts(AssetPayment source, List<AssetPayment> consumedList) {
    try {
        for (PropertyDescriptor propertyDescriptor : assetPaymentProperties) {
            Method readMethod = propertyDescriptor.getReadMethod();
            if (readMethod != null && propertyDescriptor.getPropertyType() != null && KualiDecimal.class.isAssignableFrom(propertyDescriptor.getPropertyType())) {
                KualiDecimal amount = (KualiDecimal) readMethod.invoke(source);
                if (amount != null && amount.isNonZero()) {
                    Method writeMethod = propertyDescriptor.getWriteMethod();
                    KualiDecimal consumedAmount = KualiDecimal.ZERO;
                    KualiDecimal currAmt = KualiDecimal.ZERO;
                    if (writeMethod != null) {
                        for (int i = 0; i < consumedList.size(); i++) {
                            currAmt = (KualiDecimal) readMethod.invoke(consumedList.get(i));
                            consumedAmount = consumedAmount.add(currAmt != null ? currAmt : KualiDecimal.ZERO);
                        }
                    }
                    if (!consumedAmount.equals(amount)) {
                        AssetPayment lastPayment = consumedList.get(consumedList.size() - 1);
                        writeMethod.invoke(lastPayment, currAmt.add(amount.subtract(consumedAmount)));
                    }
                }
            }
        }
    }
    catch (Exception e) {
        throw new RuntimeException(e);
    }

}
 
Example 17
private List<Parameter> extractParametersFromModelAttributeAnnotation(Type type, Map<Class<?>, Annotation> annotations) {
    ModelAttribute modelAttribute = (ModelAttribute)annotations.get(ModelAttribute.class);
    if ((modelAttribute == null || !hasClassStartingWith(annotations.keySet(), "org.springframework.web.bind.annotation"))&& BeanUtils.isSimpleProperty(TypeUtils.getRawType(type, null))) {
        return Collections.emptyList();
    }

    List<Parameter> parameters = new ArrayList<Parameter>();
    Class<?> clazz = TypeUtils.getRawType(type, type);
    for (PropertyDescriptor propertyDescriptor : BeanUtils.getPropertyDescriptors(clazz)) {
        // Get all the valid setter methods inside the bean
        Method propertyDescriptorSetter = propertyDescriptor.getWriteMethod();
        if (propertyDescriptorSetter != null) {
            ApiParam propertySetterApiParam = AnnotationUtils.findAnnotation(propertyDescriptorSetter, ApiParam.class);
            if (propertySetterApiParam == null) {
                // If we find a setter that doesn't have @ApiParam annotation, then skip it
                continue;
            }

            // Here we have a bean setter method that is annotted with @ApiParam, but we still
            // need to know what type of parameter to create. In order to do this, we look for
            // any annotation attached to the first method parameter of the setter fucntion.
            Annotation[][] parameterAnnotations = propertyDescriptorSetter.getParameterAnnotations();
            if (parameterAnnotations == null || parameterAnnotations.length == 0) {
                continue;
            }

            Class parameterClass = propertyDescriptor.getPropertyType();
            List<Parameter> propertySetterExtractedParameters = this.extractParametersFromAnnotation(
                    parameterClass, toMap(Arrays.asList(parameterAnnotations[0])));

            for (Parameter parameter : propertySetterExtractedParameters) {
                if (Strings.isNullOrEmpty(parameter.getName())) {
                    parameter.setName(propertyDescriptor.getDisplayName());
                }
                ParameterProcessor.applyAnnotations(new Swagger(), parameter, type, Lists.newArrayList(propertySetterApiParam));
            }
            parameters.addAll(propertySetterExtractedParameters);
        }
    }

    return parameters;
}
 
Example 18
private static void test(Class type, String name, Class expected) {
    PropertyDescriptor pd = BeanUtils.getPropertyDescriptor(type, name);
    if (name.equals(pd.getName()))
        if (!expected.equals(pd.getPropertyType()))
            throw new Error("expected " + expected + " but " + pd.getPropertyType() + " is resolved");
}
 
Example 19
protected DictionaryWrapperObject createCache(Class bean) {
    String beanName = bean.getName();
    StringBuilder wrapMethod = new StringBuilder()
            .append("public void wrap(Object id,Object bean, org.hswebframework.web.dictionary.simple.DefaultDictionaryHelper helper)")
            .append("{\n")
            .append(bean.getName()).append(" target=(").append(bean.getName()).append(")bean;\n");

    StringBuilder persistentMethod = new StringBuilder()
            .append("public void persistent(Object id,Object bean, org.hswebframework.web.dictionary.simple.DefaultDictionaryHelper helper)")
            .append("{\n")
            .append(bean.getName()).append(" target=(").append(bean.getName()).append(")bean;\n");

    PropertyDescriptor[] descriptors = BeanUtilsBean.getInstance().getPropertyUtils().getPropertyDescriptors(bean);
    boolean hasDict = false;
    for (PropertyDescriptor descriptor : descriptors) {
        Class type = descriptor.getPropertyType();
        boolean isArray = type.isArray();
        if (isArray) {
            type = type.getComponentType();
        }
        //枚举字典并且枚举数量大于64
        if (type.isEnum() && EnumDict.class.isAssignableFrom(type) && type.getEnumConstants().length >= 64) {
            String typeName = isArray ? type.getName().concat("[]") : type.getName();
            String dictId = type.getName();
            Dict dict = (Dict) type.getAnnotation(Dict.class);
            if (dict != null) {
                dictId = dict.id();
            }
            wrapMethod.append("{\n");
            wrapMethod.append(typeName).append(" dict=(").append(typeName).append(")helper.getDictEnum(id,")
                    .append("\"").append(beanName).append(".").append(descriptor.getName()).append("\"").append(",\"").append(dictId).append("\"")
                    .append(",").append(typeName).append(".class);\n");
            wrapMethod.append("target.").append(descriptor.getWriteMethod().getName()).append("(dict);\n");
            wrapMethod.append("}");

            persistentMethod.append("helper.persistent(id,")
                    .append("\"").append(beanName).append(".").append(descriptor.getName()).append("\"").append(",\"").append(dictId).append("\"")
                    .append(",").append(typeName).append(".class,")
                    .append("target.").append(descriptor.getReadMethod().getName()).append("()")
                    .append(");\n");

            hasDict = true;
        }
    }
    wrapMethod.append("\n}");
    persistentMethod.append("\n}");
    if (hasDict) {
        return Proxy.create(DictionaryWrapperObject.class)
                .addMethod(wrapMethod.toString())
                .addMethod(persistentMethod.toString())
                .newInstance();
    }
    return EMPTY_WRAPPER;
}
 
Example 20
private static void test(Class type, String name, Class expected) {
    PropertyDescriptor pd = BeanUtils.getPropertyDescriptor(type, name);
    if (name.equals(pd.getName()))
        if (!expected.equals(pd.getPropertyType()))
            throw new Error("expected " + expected + " but " + pd.getPropertyType() + " is resolved");
}