Java Code Examples for org.springframework.beans.BeanUtils#getPropertyDescriptor()

The following examples show how to use org.springframework.beans.BeanUtils#getPropertyDescriptor() . 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
Source Project: mPaaS   File: EntityToVoMapper.java    License: Apache License 2.0 6 votes vote down vote up
/** 单值数据类型转换,对象转换成Map */
private Object castSingleValue(MetaProperty property, Object srcValue)
		throws ReflectiveOperationException {
	if (srcValue instanceof IEntity) {
		Map<String, Object> value = new HashMap<>(2);
		// fdId
		value.put("fdId", ((IEntity) srcValue).getFdId());
		MetaEntity entity = MetaEntity.localEntity(property.getType());
		// displayProperty
		String display = entity.getDisplayProperty();
		if (StringUtils.isBlank(display)) {
			return value;
		}
		PropertyDescriptor desc = BeanUtils
				.getPropertyDescriptor(srcValue.getClass(), display);
		if (desc != null) {
			Method read = desc.getReadMethod();
			if (read != null) {
				value.put(display, read.invoke(srcValue));
			}
		}
		return value;
	}
	return srcValue;
}
 
Example 2
Source Project: mPaaS   File: ExtendPropertyAccess.java    License: Apache License 2.0 6 votes vote down vote up
public ExtendPropertyAccess(PropertyAccessStrategy strategy,
		Class containerJavaType, String propertyName) {
	this.strategy = strategy;
	PropertyDescriptor desc = BeanUtils
			.getPropertyDescriptor(containerJavaType, propertyName);
	Class<?> returnType = null;
	MetaEntity entity = MetaEntity.localEntity(containerJavaType.getName());
	MetaProperty property = entity == null ? null
			: entity.getProperty(propertyName);
	if (property != null) {
		returnType = EntityUtil.getPropertyType(property.getType());
	}
	if (returnType == null) {
		returnType = Object.class;
	}
	this.getter = new DynamicPropertyGetterSetter(propertyName, returnType,
			desc == null ? null : desc.getReadMethod());
	this.setter = new DynamicPropertyGetterSetter(propertyName, returnType,
			desc == null ? null : desc.getWriteMethod());
}
 
Example 3
private Object readProperty(Object object, String name) throws LayerException {
	if (object != null) {
		PropertyDescriptor d = BeanUtils.getPropertyDescriptor(object.getClass(), name);
		if (d != null && d.getReadMethod() != null) {
			BeanUtils.getPropertyDescriptor(object.getClass(), name);
			Method m = d.getReadMethod();
			if (!Modifier.isPublic(m.getDeclaringClass().getModifiers())) {
				m.setAccessible(true);
			}
			Object value;
			try {
				value = m.invoke(object);
			} catch (Throwable t) {
				throw new LayerException(t, ExceptionCode.FEATURE_MODEL_PROBLEM);
			}
			return value;
		} else {
			return null;
		}
	} else {
		return null;
	}
}
 
Example 4
Source Project: jdal   File: FormatUtils.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Get a formatter for class and property name
 * @param clazz the class
 * @param propertyName the property name
 * @return the formatter or null if none
 */
public static Formatter<?> getFormatter(Class<?> clazz, String propertyName) {
	PropertyDescriptor pd = BeanUtils.getPropertyDescriptor(clazz, propertyName);
	if (pd != null) {
		NumberFormat format = getAnnotation(pd, NumberFormat.class);
		if (format != null) {
			return (Formatter<?>) numberFormatFactory.getPrinter(format, pd.getPropertyType());
		}
		
		PeriodFormat periodFormat = getAnnotation(pd, PeriodFormat.class);
		if (periodFormat != null)
			return new PeriodFormatter();
	}
	
	return null;
}
 
Example 5
Source Project: mPass   File: VoToEntityMapper.java    License: Apache License 2.0 6 votes vote down vote up
/** 创建一对多级联的子项 */
private Object newCascadeChild(Class<?> clazz, MapperContext context)
		throws Exception {
	Object result = ReflectUtil.newInstance(clazz);
	if (StringUtils.isNotBlank(context.metaProp.getMappedBy())) {
		// 设置反向关系
		String mappedBy = context.metaProp.getMappedBy();
		PropertyDescriptor desc = BeanUtils.getPropertyDescriptor(clazz,
				mappedBy);
		if (desc == null) {
			return result;
		}
		Method method = desc.getWriteMethod();
		if (method == null) {
			return result;
		}
		method.invoke(result, context.target);
	}
	return result;
}
 
Example 6
Source Project: mPass   File: ReflectUtil.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * 获取bean的字段值
 */
@SuppressWarnings("unchecked")
public static <T> T getProperty(Object bean, String prop)
		throws ReflectiveOperationException {
	if (bean == null) {
		return null;
	}
	if (bean instanceof Map<?, ?>) {
		return (T) ((Map<?, ?>) bean).get(prop);
	}
	PropertyDescriptor desc = BeanUtils
			.getPropertyDescriptor(bean.getClass(), prop);
	if (desc == null) {
		throw new NoSuchFieldException();
	}
	Method method = desc.getReadMethod();
	if (method == null) {
		throw new NoSuchMethodException();
	}
	return (T) method.invoke(bean);
}
 
Example 7
private boolean isValidPropertyName(AbstractConfig dubboConfigBean, String propertyValue) {
    boolean valid = true;
    String propertyName = "name";
    // AbstractConfig.checkName(String,String)
    Method method = findMethod(AbstractConfig.class, "checkName", String.class, String.class);
    try {
        if (method != null) {
            if (!method.isAccessible()) {
                method.setAccessible(true);
            }
            if (BeanUtils.getPropertyDescriptor(dubboConfigBean.getClass(), propertyName) != null) {
                invokeMethod(method, null, propertyName, propertyValue);
            }
        }
    } catch (IllegalStateException e) {
        valid = false;
    }

    return valid;
}
 
Example 8
Source Project: mPaaS   File: AbstractMapper.java    License: Apache License 2.0 5 votes vote down vote up
public Object getSourceValue(String name)
        throws ReflectiveOperationException {
    PropertyDescriptor desc = BeanUtils
            .getPropertyDescriptor(source.getClass(), name);
    if (desc == null) {
        return null;
    }
    Method read = desc.getReadMethod();
    if (!accessable(read)) {
        return null;
    }
    return read.invoke(source);
}
 
Example 9
Source Project: jdal   File: ListTableModel.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Get a primary key of entity in the list
 * @param row row of model
 * @return the primary key of model, if any
 */
private Object getPrimaryKey(Object row) {
	if (BeanUtils.getPropertyDescriptor(modelClass, id) == null)
		return row;
	
	BeanWrapper wrapper = PropertyAccessorFactory.forBeanPropertyAccess(row);
	return wrapper.getPropertyValue(id);
}
 
Example 10
Source Project: bdf3   File: JpaUtil.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * 根据属性收集属性对应的数据
 * @param source 源
 * @param propertyName 属性名
 * @param <T> 范型
 * @return source集合每个对象的propertyName属性值的一个集合
 */
@SuppressWarnings({ "rawtypes", "unchecked" })
public static <T> Set<T> collect(Collection<?> source, String propertyName) {
	if (CollectionUtils.isEmpty(source)) {
		return Collections.EMPTY_SET;
	}
	Set result = new HashSet(source.size());

	for (Object obj : source) {
		Object value = null;
		if (obj instanceof Map) {
			value = ((Map) obj).get(propertyName);
		} else if (obj instanceof Tuple) {
			value = ((Tuple) obj).get(propertyName);
		} else if (EntityUtils.isEntity(obj)) {
			value = EntityUtils.getValue(obj, propertyName);
		} else if (obj != null) {
			PropertyDescriptor pd = BeanUtils.getPropertyDescriptor(obj.getClass(), propertyName);
			try {
				value = pd.getReadMethod().invoke(obj, new Object[]{});
			} catch (IllegalAccessException | IllegalArgumentException
					| InvocationTargetException e) {
				e.printStackTrace();
			}
		}
		if (value != null) {
			result.add(value);
		}
	}
	return result;
}
 
Example 11
@Override
public void valid(Annotation annotation, Object target, final Field field, final Errors errors) throws Exception {
	PropertyDescriptor propertyDescriptor = BeanUtils.getPropertyDescriptor(target.getClass(), field.getName());
	Method reader = propertyDescriptor.getReadMethod();
	Object property = reader.invoke(target);
	validProperty(annotation, property,
		(errorCode, message) -> errors.rejectValue(field.getName(), errorCode, message));
}
 
Example 12
Source Project: jdal   File: ComboBoxFieldBuilder.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Fill the ComboBox with items from PersistentService
 * @param combo ComboBox to fill
 * @param clazz Class of Bean containing property name
 * @param name property name
 */
protected void fillComboBox(ComboBox combo, Class<?> clazz, String name) {
	PropertyDescriptor pd = BeanUtils.getPropertyDescriptor(clazz, name);
	Dao<?, Serializable> service = 
		persistentServiceFactory.createPersistentService(pd.getPropertyType());
	// fill combo
	Iterator<?>  iter = service.getAll().iterator();
	while(iter.hasNext())
		combo.addItem(iter.next());
}
 
Example 13
Source Project: youkefu   File: UKTools.java    License: Apache License 2.0 5 votes vote down vote up
public static void copyProperties(Object source, Object target,String... ignoreProperties)  
        throws BeansException {  
  
    Assert.notNull(source, "Source must not be null");  
    Assert.notNull(target, "Target must not be null");  
  
    Class<?> actualEditable = target.getClass();  
    PropertyDescriptor[] targetPds = BeanUtils.getPropertyDescriptors(actualEditable);  
    List<String> ignoreList = (ignoreProperties != null) ? Arrays.asList(ignoreProperties) : null;  
  
    for (PropertyDescriptor targetPd : targetPds) {  
        Method writeMethod = targetPd.getWriteMethod();  
        if (writeMethod != null && (ignoreProperties == null || (!ignoreList.contains(targetPd.getName())))) {  
            PropertyDescriptor sourcePd = BeanUtils.getPropertyDescriptor(source.getClass(), targetPd.getName());  
            if (sourcePd != null && !targetPd.getName().equalsIgnoreCase("id")) {  
                Method readMethod = sourcePd.getReadMethod();  
                if (readMethod != null &&  
                        ClassUtils.isAssignable(writeMethod.getParameterTypes()[0], readMethod.getReturnType())) {  
                    try {  
                        if (!Modifier.isPublic(readMethod.getDeclaringClass().getModifiers())) {  
                            readMethod.setAccessible(true);  
                        }  
                        Object value = readMethod.invoke(source);  
                        if(value != null){  //只拷贝不为null的属性 by zhao  
                            if (!Modifier.isPublic(writeMethod.getDeclaringClass().getModifiers())) {  
                                writeMethod.setAccessible(true);  
                            }  
                            writeMethod.invoke(target, value);  
                        }  
                    }  
                    catch (Throwable ex) {  
                        throw new FatalBeanException(  
                                "Could not copy property '" + targetPd.getName() + "' from source to target", ex);  
                    }  
                }  
            }  
        }  
    }  
}
 
Example 14
Source Project: mPass   File: AbstractMapper.java    License: Apache License 2.0 5 votes vote down vote up
public Object getSourceValue(String name)
        throws ReflectiveOperationException {
    PropertyDescriptor desc = BeanUtils
            .getPropertyDescriptor(source.getClass(), name);
    if (desc == null) {
        return null;
    }
    Method read = desc.getReadMethod();
    if (!accessable(read)) {
        return null;
    }
    return read.invoke(source);
}
 
Example 15
public BeanFeatureModel(VectorLayerInfo vectorLayerInfo, int srid, EntityAttributeService entityMappingService)
		throws LayerException {
	this.vectorLayerInfo = vectorLayerInfo;
	this.entityMappingService = entityMappingService;

	try {
		beanClass = Class.forName(vectorLayerInfo.getFeatureInfo().getDataSourceName());
	} catch (ClassNotFoundException e) {
		throw new LayerException(ExceptionCode.FEATURE_MODEL_PROBLEM, "Feature class "
				+ vectorLayerInfo.getFeatureInfo().getDataSourceName() + " was not found", e);
	}
	this.srid = srid;
	PropertyDescriptor d = BeanUtils.getPropertyDescriptor(beanClass, getGeometryAttributeName());
	Class geometryClass = d.getPropertyType();
	if (Geometry.class.isAssignableFrom(geometryClass)) {
		wkt = false;
	} else if (geometryClass == String.class) {
		wkt = true;
	} else {
		throw new LayerException(ExceptionCode.FEATURE_MODEL_PROBLEM, "Feature "
				+ vectorLayerInfo.getFeatureInfo().getDataSourceName() + " has no valid geometry attribute");
	}

	FeatureInfo featureInfo = vectorLayerInfo.getFeatureInfo();
	for (AbstractAttributeInfo info : featureInfo.getAttributes()) {
		addAttribute(null, info);
	}
	entityMapper = new BeanEntityMapper();
}
 
Example 16
Source Project: mPass   File: VoToEntityMapper.java    License: Apache License 2.0 5 votes vote down vote up
/** 拷贝单个属性 */
@SuppressWarnings("unchecked")
private void copyFixedProperty(MapperContext context, Object srcValue)
		throws Exception {
	// 目标可读/写
	context.targetDesc = BeanUtils.getPropertyDescriptor(
			context.target.getClass(), context.propName);
	if (context.targetDesc == null) {
		return;
	}
	Method read = context.targetDesc.getReadMethod();
	if (!accessable(read)) {
		return;
	}
	Method write = context.targetDesc.getWriteMethod();
	if (!accessable(write)) {
		return;
	}
	// 读取目标值
	Object targetValue = read.invoke(context.target);
	Class<?> targetClass = getTargetClass(context);
	if (context.metaProp.isCollection()) {
		// 数组
		if (targetValue == null) {
			targetValue = new ArrayList<>();
			write.invoke(context.target, new Object[] { targetValue });
		}
		copyListValue(context, (Collection<?>) srcValue,
				(Collection<Object>) targetValue, targetClass);
	} else {
		// 单值
		Object value = castSingleValue(context, srcValue, targetValue,
				targetClass);
		if (value != targetValue) {
			checkVersion(value, targetValue, context);
			write.invoke(context.target, value);
		}
	}
}
 
Example 17
Source Project: mPaaS   File: PageQueryTemplate.java    License: Apache License 2.0 4 votes vote down vote up
/**
 * 添加选择列,支持a.b.c,仅用于转vo的情况
 */
private void appendSelectColumn4VO(QueryContextImpl<E, Tuple> context,
		String propName, List<MetaProperty> props,
		List<Selection<?>> selects, ViewInfo root) {
	Class<?> clazz = viewClass;
	ViewInfo current = root;
	int n = props.size() - 1;
	// 层级遍历
	for (int i = 0; i < props.size(); i++) {
		MetaProperty prop = props.get(i);
		PropertyDescriptor desc = BeanUtils.getPropertyDescriptor(clazz,
				prop.getName());
		if (desc == null || desc.getWriteMethod() == null
				|| desc.getReadMethod() == null) {
			throw new ParamsNotValidException(
					StringHelper.join(propName, "对应的VO的属性不支持读/写"));
		}
		ViewInfo child = current.getOrAddChild(desc);
		current = child;
		if (prop.isCollection()) {
			// 列表对象
			child.arrayElementType = getListActualType(clazz, desc);
			if (child.arrayElementType == null) {
				throw new ParamsNotValidException(
						StringHelper.join(propName, "无法获取列表的实际类型"));
			}
			clazz = child.arrayElementType;
		} else {
			// 单值对象
			clazz = desc.getPropertyType();
		}
		if (i == n) {
			// 最后一级
			if (MetaConstant.isAssociation(prop.getType())) {
				// c是子对象,遍历对象下的属性
				MetaEntity meta = MetaEntity.localEntity(prop.getType());
				if (meta == null) {
					return;
				}
				PropertyDescriptor[] childDescs = BeanUtils
						.getPropertyDescriptors(clazz);
				for (PropertyDescriptor childDesc : childDescs) {
					if (childDesc.getWriteMethod() == null) {
						continue;
					}
					// 属性必须有在数据库中,并且不能是外键对象,显示类型允许在列表展现
					String name = childDesc.getName();
					MetaProperty childProp = meta.getProperty(name);
					if (childProp == null
							|| childProp.getShowType() != ShowType.ALWAYS
							|| MetaConstant
									.isAssociation(childProp.getType())) {
						continue;
					}
					// 追加子对象属性
					child = current.getOrAddChild(childDesc);
					appendSelectAndLangColumn(context, childProp,
							StringHelper.join(propName, '.', name), selects,
							child);
				}
			} else {
				// c是普通属性,直接追加
				if ("fdId".equals(propName)) {
					current.index = 0;
				} else {
					appendSelectAndLangColumn(context, prop, propName,
							selects, current);
				}
			}
		}
	}
}
 
Example 18
Source Project: youkefu   File: PropertiesEventUtils.java    License: Apache License 2.0 4 votes vote down vote up
public static List<PropertiesEvent> processPropertiesModify(HttpServletRequest request , Object newobj , Object oldobj,String... ignoreProperties){
	List<PropertiesEvent> events = new ArrayList<PropertiesEvent>() ;
	//
	String[] fields = new String[]{"id" , "orgi" , "creater" ,"createtime" , "updatetime"} ; 
	List<String> ignoreList = new ArrayList<String>(); 
	ignoreList.addAll(Arrays.asList(fields)) ;
	if((ignoreProperties != null)){
		ignoreList.addAll(Arrays.asList(ignoreProperties));
	}
	PropertyDescriptor[] targetPds = BeanUtils.getPropertyDescriptors(newobj.getClass());
	for (PropertyDescriptor targetPd : targetPds) {  
        Method newReadMethod = targetPd.getReadMethod();  
        if (oldobj!=null && newReadMethod != null && (ignoreProperties == null || (!ignoreList.contains(targetPd.getName())))) {  
            PropertyDescriptor sourcePd = BeanUtils.getPropertyDescriptor(oldobj.getClass(), targetPd.getName());  
            if (sourcePd != null && !targetPd.getName().equalsIgnoreCase("id")) {  
                Method readMethod = sourcePd.getReadMethod();  
                if (readMethod != null) {  
                    try {  
                    	Object newValue = readMethod.invoke(newobj);
                        Object oldValue = readMethod.invoke(oldobj);
                        
                        if(newValue != null && !newValue.equals(oldValue)){
                        	PropertiesEvent event = new PropertiesEvent();
                        	event.setField(targetPd.getName());
                        	event.setCreatetime(new Date());
                        	event.setName(targetPd.getName());
                        	event.setPropertity(targetPd.getName());
                        	event.setOldvalue(oldValue!=null && oldValue.toString().length()<100 ? oldValue.toString() : null);
                        	event.setNewvalue(newValue!=null && newValue.toString().length()<100 ? newValue.toString() : null);
                        	if(request!=null && !StringUtils.isBlank(request.getParameter(targetPd.getName()+".text"))){
                        		event.setTextvalue(request.getParameter(targetPd.getName()+".text"));
                        	}
                        	events.add(event) ;
                        }
                    }  
                    catch (Throwable ex) {  
                        throw new FatalBeanException(  
                                "Could not copy property '" + targetPd.getName() + "' from source to target", ex);  
                    }  
                }  
            }  
        }  
    }  
	return events ;
}
 
Example 19
private static Method getReadMethod(Object bean, String propertyName) {
    PropertyDescriptor pd = BeanUtils.getPropertyDescriptor(bean.getClass(), propertyName);
    if (pd == null)
        return null;
    return pd.getReadMethod();
}
 
Example 20
Source Project: sinavi-jfw   File: Beans.java    License: Apache License 2.0 2 votes vote down vote up
/**
 * 指定されたクラスの、指定された名前を持つプロパティディスクリプタを取得します。
 * @param clazz 対象クラス
 * @param propertyName プロパティ名
 * @return プロパティディスクリプタ
 */
public static PropertyDescriptor findPropertyDescriptorFor(Class<?> clazz, String propertyName) {
    Args.checkNotNull(clazz);
    return BeanUtils.getPropertyDescriptor(clazz, propertyName);
}