map与反射

map与反射的结合案例

  public void test5() throws Exception {
        HashMap map = new HashMap<>();
        map.put("name","旺财");
        map.put("age",3);
        Dog dog = getObject(map, Dog.class);
        System.out.println(dog);
    }

    public  T getObject(Map map, Class c) throws Exception {
        T t = c.newInstance();
        //1.拆开map
        Set> entries = map.entrySet();
        for (Map.Entry entry : entries) {
            String key = entry.getKey();
            //2.将map中的值存入T这个类的对象属性中
            Field f = c.getDeclaredField(key);
            f.setAccessible(true);
            f.set(t,entry.getValue());
        }
        return t;
    }

运行结果如下:
map与反射_第1张图片

你可能感兴趣的:(反射,map,反射,java)