應(yīng)用場(chǎng)景
程序有一個(gè)數(shù)據(jù)庫(kù)對(duì)象進(jìn)行update操作
如:前臺(tái)form表單提交對(duì)象Entity(from)到后臺(tái)做數(shù)據(jù)的update哥纫,但是我form的數(shù)據(jù)可能是數(shù)據(jù)庫(kù)原始對(duì)象的不完整版(缺少一些屬性未賦值),這時(shí)我先拿到id到數(shù)據(jù)庫(kù)查詢?cè)紝?duì)象Entity(data),把我from缺少的(null or "")屬性賦值替換為原始屬性值,然后在用from數(shù)據(jù)進(jìn)行數(shù)據(jù)庫(kù)層的update
注:Entity 屬性必須含有g(shù)etter()和setter()方法蛀骇,處理原理也是用的getter和setter厌秒。
原因有二:
1.規(guī)范代碼書(shū)寫(xiě)
2.有時(shí)候有特殊屬性不進(jìn)行轉(zhuǎn)換的可以不寫(xiě)getter或setter方法
使用技術(shù)
java反射 (ps:體驗(yàn)一把反射技術(shù)的強(qiáng)大)
源碼
package com.yexue.demo.reflect;
import java.beans.Introspector;
import java.beans.PropertyDescriptor;
import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* 反射的應(yīng)用
*
* @author yexue
* @example @param <T>
* @time 2017年8月26日下午12:19:01
*/
public class ObjectUtil<T> {
public static void main(String[] args) throws Exception {
ObjectUtil<Entity> util = new ObjectUtil<>();
// 模擬數(shù)據(jù)庫(kù)查詢數(shù)據(jù)
Entity data = new Entity(1, "張三", null);
System.out.println("模擬數(shù)據(jù)庫(kù)查詢數(shù)據(jù):" + data);
// 模擬前臺(tái)from數(shù)據(jù)
Entity from = new Entity(1, "", "我是張三");
System.out.println("模擬前臺(tái)from數(shù)據(jù):" + from);
/**
* 通常會(huì)把from的id拿到去查詢數(shù)據(jù)庫(kù) 然后更新from數(shù)據(jù)后做update操作
*/
util.compare(from, data);
System.out.println("更新后的from:" + from);
}
/**
* 對(duì)比兩個(gè)對(duì)象屬性值,用obj2更新obj1
*
* @param obj1
* @param obj2
* @return
* @throws Exception
*/
public T compare(T obj1, T obj2) throws Exception {
Map<String, List<Object>> map = new HashMap<String, List<Object>>();
if (obj1.getClass() == obj2.getClass()) {// 只有兩個(gè)對(duì)象都是同一類型的才有可比性
Class clazz = obj1.getClass();
// 獲取object的屬性描述
PropertyDescriptor[] pds = Introspector.getBeanInfo(clazz, Object.class).getPropertyDescriptors();
for (PropertyDescriptor pd : pds) {// 這里就是所有的屬性了
String name = pd.getName();// 屬性名
Method readMethod = pd.getReadMethod();// get方法
Method setMethod = pd.getWriteMethod();// set方法
// 在obj1上調(diào)用get方法等同于獲得obj1的屬性值
Object o1 = readMethod.invoke(obj1);
// 在obj2上調(diào)用get方法等同于獲得obj2的屬性值
Object o2 = readMethod.invoke(obj2);
if (o2 != null && !"".equals(o2) && (o1 == null || "".equals(o1) || !o1.equals(o2))) {// 比較這兩個(gè)值是否相等,不等就可以替換
setMethod.invoke(obj1, o2);
}
}
}
return obj1;
}
}
class Entity {
private int id;
private String name;
private String title;
public Entity() {
super();
}
public Entity(int id, String name, String title) {
super();
this.id = id;
this.name = name;
this.title = title;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public Entity(int id) {
this.id = id;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
@Override
public String toString() {
return "Entity [id=" + id + ", name=" + name + ", title=" + title + "]";
}
}