1. 程式人生 > 其它 >通過反射的方式實現實體類互相轉換

通過反射的方式實現實體類互相轉換

作為一名crud程式設計師,今天上午編寫一條編輯介面的時候,犯懶了。前端傳來的資料是dto,用mybatis plus的方法更新的話需要表對應的bean 一個屬性一個屬性的get、set實在是太麻煩了,同樣寫sql也是很麻煩。在下就想著寫一個工具類一勞永逸。
初入江湖不到一年時間,功力淺薄,有寫的不合適的地方,希望各位大佬踴躍指正。O(∩_∩)O

eg: 僅僅適用於有部分相同屬性名的兩個物件 。 tran 是需要的物件,traned是被轉換的物件(比如前端傳過來的dto-tran要被轉換成entity-traned)

以下是程式碼:
public static Object transformObject (Object tran,Object traned) throws InvocationTargetException, IllegalAccessException, InstantiationException, IntrospectionException {

		Class<?> tranedClass = traned.getClass();
		Field[] tranedFields = tranedClass.getDeclaredFields();

		List<Map<String,Object>> tranedAttributeList = new ArrayList<>();
		Map<String,Object> values = new HashMap<>();
		// 獲取被轉換物件不為空的屬性
		for (Field field : tranedFields) {
			if (field.getName().equals("serialVersionUID"))
				continue;
			PropertyDescriptor propertyDescriptor = new PropertyDescriptor(field.getName(), tranedClass);
			Method method = propertyDescriptor.getReadMethod();
			Object val = method.invoke(traned);
			if (val != null) {
				Map<String,Object> map = new HashMap<>();
				map.put("attributeName",field.getName());
				map.put("attributeValue",val);
				tranedAttributeList.add(map);
				values.put(field.getName(),val);
			}
		}

		Class<?> tranClass = tran.getClass();
		Field[] tranFields = tranClass.getDeclaredFields();
		// 需要轉換的屬性
		List<String> beTranedNames = new ArrayList<>();
		for (Field field : tranFields ) {
			for (Map<String,Object> map : tranedAttributeList) {
				if (map.get("attributeName").equals(field.getName())){
					beTranedNames.add(field.getName());
				}
			}
		}
		Object o = tranClass.newInstance();
		for (String name : beTranedNames) {
			PropertyDescriptor pd = new PropertyDescriptor(name, tranClass);
			Method method = pd.getWriteMethod();
			if (values.get(name) != null)
				method.invoke(o,values.get(name));
		}
		return o;
	}