反射实现对象的封装

       近期在项目中收到socket接收到的报文,将每个月的数据整理成符合json格式的数据,从前台传到后台生成pdf,其中涉及到了一个方法,我希望在此记录下,因为比较实用。

      先说说为什么要转吧?接受到的报文大致是这样的{property="12".......,list=[propert2="",........],propert3="",........]....},大概是这么一个模式,就是返回一个returnMap,包含了报文头以及循环的信息,二循环的信息依然是个Map,只不过泛型是<String,List<Dto>>,我要做的就是遍历这个含有List的Map<String,List<Dto>>,然后一一将单个集合转化为一个实体,我院额原本的数据源是{"1806":["":"",...],"1806":["":"",...]} ,这是前台传来的Json字符串,后台我将它转为Map,实现了对象的封装,现在就用代码 实现它吧!因为数据比较冗长,我做了有几个demo用于观察。

//那么如何将一个map<String,Object> 的类型转为一个对象呢?当然其中的方法很多,但最简洁的还是用反射去实现最为方便。看了我们经理写的,具有参考价值。

//第一步:先制造几个假的数据和几个需要用到的实体类
public static void main(Stirng[] args){
    Map<String,Object> map = new HashMap<String,Object>();
    List<StringDto> list = new ArrayList<StringDto>();
    StringDto dto = new StringDto();
    dto.set("a");dto.set("b");dto.set("c");
    list.add(dto);
    map.put("name","胡明明");map.put("age","25");map.put("list","list");
    //这里数据就整合完了,就是map包含了两个字符串和一个集合然后用一个实体类去拿到map的数据,实体类我就不做展示了
    ResDto resDto = new ResDto();//数据可以比map中的数据少,多则为null或“”,因为是从map中拿数据去填充这个响应的实体类
    FanShe(map,resDto);
    System.out.println(resDto);//resDto 重写了toString()方法
}

//第二步,将单个map的属性转为实体类属性
public void static FanShe(Map<String,Object> map,Obejct obj){
    Class<?> cl = obj.getClass();
    Field[] fields = cl.getDeclaredFields();//取得反射对象的所有属性
    for(int i=0;i<fields.length;i++){
        //筛选属性为private的属性
        int number = fields[i].getModifiers();//返回修饰符的int
        String str = Modifier.toString(number);//对类和成员的访问修饰符进行解码
        if("private".equals(str)){
            String property = fields[i].getName();//取得为private修饰字段的名称
            if(map.containsKey(property)){
                Class<?> mapObjClass = map.get(property).getClass();//取得map中value的反射对象
                Class<?>[] interfaceAry = mapObjClass.getInterface();//取得该类实现的接口,比如String类就[interface java.io.serializable,interface java.lang.Compable,]            
                Class<?> singleInterface = null;
                for(int j=0;j<interfaceAry .length,j++){
                    if(interfaceAry[j].equals(List.class.getName)){//java.io.serializable
                        singleInterface = interfaceAry[j];
                        break;
                    }
                }
                //因为Map中包含了List的话,去调mapObjClass.getDeclaredMethod方法时,参数的反射类型是接口类型,而不是ArrayList类类型
                if(null != singleInterface){
                    Method method = mapObjClass.getDeclaredMethod(getFuncName(property),singleInterface);
                }else{
                   Method method =  mapObjClass.getDeclaredMethod(getFuncName(property),mapObjClass);
                }
                Method.invoke(obj,map.get(property));//(调用底层的方法对象,该方法形参参数类型  类似于对象.方法  如果没有参数的话则第二个参数不填mapObjClass.getDeclaredMethod(getFuncName(property));
            }
        }  

    }
}

public static String getFuncName(String propertyStr){
    String funcNameStr = "set" + propertyStr.substring(0,1).toUpperCase() + propertyStr.substring(1);
    return funcNameStr; 
}

猜你喜欢

转载自blog.csdn.net/qq_40826106/article/details/82736324