`

根据指定的类名以及属性字符串名值对构建指定的bean实例

    博客分类:
  • Code
阅读更多
主要是反射(基本类型)的一些用法.很少用, 容易忘记, 备忘一下
public class TestUtils {
	/**
	 * 根据指定的类名以及属性字符串名值对构建指定的bean实例.
	 * @param <T>
	 * @param clazz
	 * @param str 形如"includeSkus=true,spuId=143944,queryOrder=desc,startsMin=2009-07-24 12:08:46"这样的字符串
	 * @return
	 * @throws Exception
	 */
	public static <T> T createBean(Class<T> clazz, String str) throws Exception{
		T bean = clazz.newInstance();
		String[] properties = StringUtils.split(str, ",");
		if (properties == null || properties.length == 0) {
			return bean;
		}
		

		for (String property : properties) {
			String[] pair = StringUtils.split(property, "=");
			if (pair.length != 2) {
				continue;
			}
			String name = pair[0];
			String value = pair[1];
            if (StringUtils.equals(value, "null")) {
                continue;
            }

			Class<?> type = PropertyUtils.getPropertyType(bean, name);
			Object realValue = null;
			// 目前只支持字符串, boolean, 日期, 数字(long, int等)
            if (type == null) {
                continue;
            }

			if (type == String.class) {
				realValue = value;
			}else if (type.isPrimitive() && type == Boolean.TYPE){
				realValue = Boolean.valueOf(value);
			}else if (Date.class.isAssignableFrom(type)){
				realValue = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss").parse(value);
			}else if (Number.class.isAssignableFrom(type)) {
				realValue = type.getConstructor(String.class).newInstance(value);
			}else if (type.isPrimitive()){
				if (type == Long.TYPE ) {
					realValue = Long.valueOf(value);
				}else if (type == Integer.TYPE ) {
					realValue = Integer.valueOf(value);
				}else if (type == Float.TYPE) {
					realValue = Float.valueOf(value);					
				}else if (type == Short.TYPE) {
					realValue = Short.valueOf(value);					
				}else if (type == Double.TYPE) {
					realValue = Double.valueOf(value);					
				}else {
					continue;
				}
			}else {
				continue;
			}
			
			PropertyUtils.setProperty(bean, name, realValue);
			
		}
		
		return bean;
	}
	
	@Test
	public void testBeanPropertyUtils() throws Exception{
		TempBean bean = createBean(TempBean.class, "id=1234,includeSkus=true,spuId=143944,queryOrder=desc,startsMin=2009-07-24 12:08:46");
		Assert.assertTrue(bean.isIncludeSkus());
		Assert.assertEquals(bean.getId(), 1234L);
		Assert.assertEquals(bean.getSpuId(), (Long)143944L);
		Assert.assertEquals(bean.getQueryOrder(), "desc");
		Assert.assertEquals(bean.getStartsMin(), new SimpleDateFormat("yyyy-MM-dd hh:mm:ss").parse("2009-07-24 12:08:46"));
	}
}
分享到:
评论
1 楼 osacar 2012-02-10  
是啊,我也要标记一下,我也忘了

相关推荐

Global site tag (gtag.js) - Google Analytics