Recursively read any Java object and infer complex types into a hash map

I need to write a utility program that takes an empty HashMap and any object as arguments and returns a 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 many objects inside it, and in these objects there are many children, and the line continues.

My utility should be general enough to recursively read all children, until it hits the primitives in each object, puts each of these objects in the hasp map, and returns it back. This is something like a parent who will be there on the map. but individual children will also be present as subsequent entries on the map.

I am new to java analysis and I have looked through some tutorials and examples on the net. Not very sure how to proceed. I believe that this is one of the frequent requirements that experts and professionals could encounter here.

Reach help me with a starting point on this. If there are any open source bean utilities available for this? if yes, please let me know.

+3
source share
2 answers

Something like this should do this:

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 in one map. You may need to create a map for each stage of the recursion if you want sub-pages for children. I can also give you this code if you need it.

, , , .

+5
+4

Source: https://habr.com/ru/post/1780244/


All Articles