If i understood what you mean, your solution should be the following:
import java.lang.reflect.Array;
import java.lang.reflect.Field;
import java.lang.reflect.Modifier;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class ReflectionToMap {
private static void toMap(Object obj, Map<String, Object> map, boolean includeSuperclass) {
Class<?> cls = obj.getClass();
try {
if (cls.isArray()) {
for (int i = 0; i < Array.getLength(obj); i++)
map.put("" + i, Array.get(obj, i));
} else {
while (cls != null && !cls.isInterface()) {
Field[] fields = cls.getDeclaredFields();
for (Field field : fields) {
if (Modifier.isStatic(field.getModifiers()))
continue;
boolean accessible = field.isAccessible();
field.setAccessible(true);
Object value = field.get(obj);
field.setAccessible(accessible);
if (includeSuperclass)
map.put(cls.getCanonicalName() + "." + field.getName(), value);
else
map.put(field.getName(), value);
}
if (includeSuperclass)
cls = cls.getSuperclass();
else
return;
}
}
} catch (Exception e) {
System.err.println("Something gone wrong...");
e.printStackTrace();
}
}
public static void main(String[] args) {
List<String> list = new ArrayList<>();
list.add("hello");
list.add("world");
Map<String, Object> map = new HashMap<>();
toMap(list, map, true);
System.out.println(map);
map.clear();
toMap(list, map, false);
System.out.println(map);
}
}
The method toMap() takes an object to convert to map and the map that will contains the result. The method includes fields from superclasses, too. Each field name, includes the canonical name of the class/abstract class, which it belongs to.
The included main method outputs the following:
{java.util.ArrayList.elementData=[Ljava.lang.Object;@70dea4e, java.util.ArrayList.size=2, java.util.AbstractList.modCount=2}
{size=2, elementData=[Ljava.lang.Object;@70dea4e}
The catched exception cannot be thrown, because the access to fields is safe.
You can use the toMap() method in the toMap() method of your class, too.
As you see, this method accepts a boolean to inhibit the inclusion of fields from superclasses. In this case it does not include the canonical name of the class in map keys.
See that if obj is array, the map will be something like:
1 -> obj1
2 -> obj2
3 -> obj3
...and so on...
HashMapis used for someother key-value pair operation in another function.