1. 程式人生 > >【BeanUtils】自己寫的BeanUtils的巢狀使用

【BeanUtils】自己寫的BeanUtils的巢狀使用

其實不打算寫的,因為和前面的是一樣的,不過既然有人問起,我就寫一下吧。

MyBeanUtils

這是核心的類:

通過這個類來返回一個bean物件的。
你給的引數是bean的class和封裝的Map物件。

package cn.hncu.beanUtils;

import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.Map;

/**
 * @author 陳浩翔
 *
 * 2016-8-25
 */
public class MyBeanUtils { public static<T> T populate(Class<T> cls ,Map<String, Object> map) throws InstantiationException, IllegalAccessException, IllegalArgumentException, InvocationTargetException, NoSuchMethodException, SecurityException{ T obj = null; //1、用類反射new出物件
obj = cls.newInstance(); //2 再用類反射對新new的物件設定屬性值(必須遵守Java設定規範)--即通過setter方法設定 //2.1遍歷出所有該類宣告的屬性 Field flds[] = cls.getDeclaredFields();//getDeclaredFields()返回Class中所有的欄位,包括私有欄位; for(Field fld:flds){ //獲取該fld物件所代表的屬性名 String fldName = fld.getName(); //根據屬性名,到map中去讀取資料,只有資料非空才需要給該屬性設定值
Object value = map.get(fldName); if(value==null){//如果map中不存在對應的屬性資料,我們在這裡給出提示資訊 System.out.println(fldName+"的資料為空"); }else{ //如果map中存在對應的屬性資料,則由屬性名得出它的setter方法的名字 String mothodName = "set"+fldName.substring(0, 1).toUpperCase()+fldName.substring(1); //根據方法名和引數的資料型別(其實就是屬性的型別),獲得Method物件 Class<?> paramTypes[] = new Class[1]; paramTypes[0] = fld.getType(); Method method = cls.getDeclaredMethod(mothodName, paramTypes); //呼叫該method物件所代表的方法 Object args[] = new Object[1]; args[0]=value; method.invoke(obj, args); } } return obj; } }

Address

package cn.hncu.domain;

/**
 * @author 陳浩翔
 *
 * 2016-8-25
 */
public class Address {
    private String province;//省份
    private String city;//城市
    public Address() {
    }
    public Address(String province, String city) {
        this.province = province;
        this.city = city;
    }
    public String getProvince() {
        return province;
    }
    public void setProvince(String province) {
        this.province = province;
    }
    public String getCity() {
        return city;
    }
    public void setCity(String city) {
        this.city = city;
    }
    @Override
    public String toString() {
        return "Address [province=" + province + ", city=" + city + "]";
    }
}

Person

package cn.hncu.domain;

import java.util.List;
import java.util.Map;

/**
 * @author 陳浩翔
 *
 * 2016-8-25
 */
public class Person {
    private String name;
    private int age;
    private Address address;
    private List lists;
    private Map map;
    public Person() {
        super();
    }
    public Person(String name, int age, Address address, List lists, Map map) {
        super();
        this.name = name;
        this.age = age;
        this.address = address;
        this.lists = lists;
        this.map = map;
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public int getAge() {
        return age;
    }
    public void setAge(int age) {
        this.age = age;
    }
    public Address getAddress() {
        return address;
    }
    public void setAddress(Address address) {
        this.address = address;
    }
    public List getLists() {
        return lists;
    }
    public void setLists(List lists) {
        this.lists = lists;
    }
    public Map getMap() {
        return map;
    }
    public void setMap(Map map) {
        this.map = map;
    }

    @Override
    public String toString() {
        return "Person [name=" + name + ", age=" + age + ", address=" + address
                + ", lists=" + lists + ", map=" + map + "]";
    }

}

測試方法:

@Test
    @SuppressWarnings({ "rawtypes", "unchecked" })
    public void test2() {
        Map<String, Object> p = new HashMap();
        p.put("name", "Jack");
        p.put("age", 100);
        p.put("address", new Address("湖南", "長沙"));

        List lists = new ArrayList();
        lists.add(new Book("B001", "紅樓夢", 25.00, 53.23, 500));
        lists.add(new User("U001", "李四", 25));
        lists.add("巢狀使用");
        p.put("lists", lists);

        Map map = new HashMap();
        map.put("user", new User("MU002", "MapUser", 30));
        map.put("string", "map中的字串");
        p.put("map", map);

        try {
            Person person = MyBeanUtils.populate(Person.class, p);

            System.out.println(person);

        } catch (ReflectiveOperationException e) {
            e.printStackTrace();
        }
    }

裡面的Book和User類也就是一個bean物件而已。
其實全部可以寫空參構造的,我為了方便,就多寫了有值的構造方法了。

輸出結果:

Person [name=Jack, age=100, address=Address [province=湖南, city=長沙], lists=[Book [uuid=B001, name=紅樓夢, inPrice=25.0, outPrice=53.23, num=500], User [uuid=U001, name=李四, age=25], 巢狀使用], map={string=map中的字串, user=User [uuid=MU002, name=MapUser, age=30]}]

其實和普通的使用沒有什麼不同的。
無非是外面再巢狀一層罷了~

完整原始碼連結: