用父类对象给子类对象赋值数据

在写毕业设计的时候遇到了一些小问题,当创建一个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));
	}
}

主要是通过反射来实现的,主要思路如下:

  1. 取父类的属性名称,首字符转大写。
  2. 遍历父类的方法,找到包含第一步属性名的方法。
  3. 根据方法参数个数判断是get还是set,boolean类型的属性的get方法是isXxxx这个没有什么关系。
  4. 进行方法调用,父类对象调get方法,子类对象调set方法。

PO类:对应数据库表的类,属性对应数据库表字段。

VO类:业务层之间用来传递数据的,可能和PO类属性相同,也可能多出几个属性。

猜你喜欢

转载自www.cnblogs.com/Vaxy/p/12670521.html