关于内省Introspector-工作小结6.8.20

今天在工作中,遇到了一个比效复杂,但不困难的,,,困扰吧。
是这样的,我从数据库中,读取出了最近七天的数据(当然是个list,属性值和后面的dto中属性值一样),然后我需要按天数把它装进一个dto(这个dto里包含了一整天的数据,而一天的数据不超过10条)。举个粟子吧

public class user{
	private String id1;
	private String name1;
	private String sex1;
	private String date1;

	private String id2;
	private String name2;
	private String sex2;
	private String date2;

	...
	private String id10;
	private String name10;
	private String sex10;
	private String date10;
}

按照以前的做法,肯定就是遍历数组,然后根据日期,把在同一天的数据,一条一条的set进这个dto,但问题是这个dto的属性很多,这样做的话,就会有一大段重复的代码,显得很冗余。对于有强迫症的我来说,这是绝对不能容忍的。
在经过长时间的面向百度编程之后,我发现了两个神奇的玩意儿:Introspector类。简单说明一下:
内省(Introspector) ,是Java 语言对 JavaBean 类属性、事件的一种缺省处理方法。
而在内省的类库里,有一个PropertyDescriptor类,表示JavaBean类通过存储器导出一个属性。主要方法:

  1. getPropertyType(),获得属性的Class对象;
  2. getReadMethod(),获得用于读取属性值的方法;
  3. getWriteMethod(),获得用于写入属性值的方法;
  4. hashCode(),获取对象的哈希值;
  5. setReadMethod(Method readMethod),设置用于读取属性值的方法;
  6. setWriteMethod(Method writeMethod),设置用于写入属性值的方法。
    主要用法:
    a)通过PropertyDescriptor类操作Bean的属性;
    b)通过Introspector类获得Bean对象的 BeanInfo,然后通过 BeanInfo 来获取属性的描述器( PropertyDescriptor ),通过这个属性描述器就可以获取某个属性对应的 getter/setter 方法,然后通过反射机制来调用这些方法。
    这里我们使用2、3方法,和a用法
public class Util{
	public static void setProperty(User user,String propertyName,String propertyValue) throw Exception{
		//获取name属性的描述器
		PropertyDescriptor propDesc=new PropertyDescriptor(name,User.class);
		//获取name属性的set方法
		Method methodSetName=propDesc.getWriteMethod();
		propertyValue = "wong"; 
		//赋值,等同于user.setName("wong")
	    methodSetName.invoke(user, propertyValue);
	    System.out.println("set name:"+user.getName());
	}

	public static String getProperty(User user,String propertyName) throw Exception){
		PropertyDescriptor properDesc = new PropertyDescriptor(String propertyName,User.class);
		Method methodGetName = properDsec.getReadMethod();
		return methodGetName.invoke(user);
	}
}

第一个方法的运行结果为:set name:wong
有了以上的工具类,我们就可以愉(tou)快(lan)地解决上面那个困扰了。
由于list和dto中的属性值一致,我们可以用一个数组来装他们的属性值

//前后无关代码均省略
String[] propers = new String["id","name","sex","age"];
int z = 0;
for(int i=0;i<7;i++){
	z = 0;
	for(User user : list){//遍历每一条数据
		if(user是符合第i天的数据){//如果是第i天的数据
			z++;
			User userDto = new User();
			for(int j=0;j<propers.length;j++){//把user装进下标为z的属性值里
				String value = Util.setProperty(user,propers[j]);
				//等同于userDto.setName1(value)
				Util.setProperty(userDto,propers[j]+z,value);
			}
		}
	}
}	

以上,可完成对冗余代码的简写(但是感觉更复杂了呢=.=)
总之,这是一种思想,虽然在当前情景可能确实更复杂,但。。。但总有一天,能有用的吧。。。嗯。。希望有这一天吧。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值