递归读取任何java对象并将复杂类型提取到哈希图中 [英] Recursively reading any java Object and pulling out complex types into a hash map

查看:184
本文介绍了递归读取任何java对象并将复杂类型提取到哈希图中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要编写一个实用程序,该程序将接受空白的HashMap和任何对象作为参数并返回HashMap

I need to write a utility program which would accept a blank HashMap and any object as arguments and return the HashMap

public HashMap returnMap(HashMap map,Object parseThisObject){

//logic to strip all children, children of children...... and place it in HashMap
//return map

}

此对象中包含许多对象,并且其中的这些对象具有许多子代,并且沿袭不断.

This object contains a lot of objects within it and those objects within has a lot of children and the lineage goes on.

我的实用程序必须足够通用,以递归方式读取所有子级,直到它击中每个对象中的基元,然后将这些对象中的每个对象放置在hasp映射中,然后将其返回. 就像父母会在地图上一样.但个别孩子也将作为后续条目出现在地图中.

My utility must be generic enough to recursively read through all children until it hits primitives in each object, place each of those objects in the hasp map and return it back. This is something like the parent would be there in the map. but the individual children also would be there as sub sequent entries in the map.

我是java反射的新手,并且在网上浏览了一些教程和示例.对如何进行不是很自信.我认为这是专家和专业人员可能经常遇到的需求之一.

I am new to java reflection and I went through some tutorials and examples on the net. Not very confident about how to proceed. I believe this is one of the frequent requirements experts and professionals over here might have faced.

请帮助我提供一个起点.是否有任何可用的Bean实用程序开源来做到这一点?如果是这样,请告诉我.

Plese help me with a starting point on this. If there is any bean utilities open source available to do this? if so please let me know.

推荐答案

应该执行以下操作:

public void fillMap(HashMap<String, Object> map, Object bean) {
    try {
        BeanInfo info = Introspector.getBeanInfo(bean.getClass());
        PropertyDescriptor[] props = info.getPropertyDescriptors();
        for (int i = 0; i < props.length; i++) {
            Method reader = props[i].getReadMethod();
            if (reader != null && !props[i].getName().equals("class")) {
                Object invoke = reader.invoke(bean, new Object[] {});
                if (invoke != null) {
                    if (!reader.getReturnType().isPrimitive()) {
                        fillMap(map, invoke);
                    } else {
                        map.put(props[i].getName(), invoke);
                    }
                }
            }
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
}

这当然会将所有对象的所有字段都放在一个地图中.如果要为子级创建子映射,则可能必须为每个递归步骤创建一个映射.如果您需要的话,我也可以给您代码.

this of course puts all fields from all objects into one map. You might have to create a map for each recursion step if you want submaps for children. I can give you that code as well if you need it.

没有映射返回,因为已将传递给该方法的映射填满.

There is no return of a map, because the one that is passed to the method is filled.

这篇关于递归读取任何java对象并将复杂类型提取到哈希图中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆