用父类对象给子类对象赋值数据
在写毕业设计的时候遇到了一些小问题,当创建一个VO类的时候,继承原先的PO类再添加新的属性比较快捷方便,但是将PO类转换成VO类就会需要先get再set所有属性。虽然说是面向ctrl+c、ctrl+v编程,但是还是想偷懒,所以有了以下代码:
/**
 * 将父类对象的属性值转储到子类对象中,仅限于get(is)方法set方法规范且并存,更适用于数据库实体类,不适用于功能性类
 * @param <T>
 * @param son 子类对象
 * @param father 父类对象
 * @throws Exception
 */
public static <T> void dump(T son, T father) throws Exception {
	//判断是否是子类
	if(son.getClass().getSuperclass() != father.getClass()) {
		throw new Exception("son is not subclass of father");
	}
	Class<? extends Object> fatherClass = father.getClass();
	//父类属性
	Field[] fatherFields = fatherClass.getDeclaredFields();
	//父类的方法
	Method[] fatherMethods = fatherClass.getDeclaredMethods();
	for (Field field : fatherFields) {
		StringBuilder sb = new StringBuilder(field.getName());
		//首字母转大写
		sb.setCharAt(0, Character.toUpperCase(sb.charAt(0)));
		Method get = null, set = null;
		//遍历找属性get(is)方法和set方法
		for (Method method : fatherMethods) {
			if (method.getName().contains(sb)) {
				//get方法或is方法
				if(method.getParameterCount() == 0) {
					get = method;
				} else {//set方法
					set = method;
				}
			}
		}
		set.invoke(son, get.invoke(father));
	}
}主要是通过反射来实现的,主要思路如下:
- 取父类的属性名称,首字符转大写。
- 遍历父类的方法,找到包含第一步属性名的方法。
- 根据方法参数个数判断是get还是set,boolean类型的属性的get方法是isXxxx这个没有什么关系。
- 进行方法调用,父类对象调get方法,子类对象调set方法。
PO类:对应数据库表的类,属性对应数据库表字段。
VO类:业务层之间用来传递数据的,可能和PO类属性相同,也可能多出几个属性。
相关推荐
  Greatemperor    2020-07-18  
   Wonder的学习    2020-06-08  
   卷卷萌    2020-04-20  
   Ericbig    2020-03-03  
   madewobadan    2020-01-13  
   duanlove技术路途    2019-12-28  
   georgeandgeorge    2019-10-31  
   ustcrding    2012-02-06  
   x青年欢乐多    2019-05-07  
   austindev    2017-09-27  
   bigcactus    2012-06-14  
   yinbaoshiguang    2019-07-01  
   刘小文    2016-11-16  
   SilentPaladin    2014-07-24  
   CherrylinORC    2013-04-10  
   jddlcg    2012-09-17  
   longxx    2012-04-18  
   zgwyfz    2016-08-07  
   anqier    2019-06-27  
 