Here is a simple reflexive / recursive example.
You should know that there are some problems with the conversion, as you asked:
- Card keys must be unique.
- Java allows classes to call their private fields the same name as a private field that belongs to an inherited class.
This example does not address these issues because I'm not sure how you want to address them (if you do). If your beans inherits from something other than Object , you need to change your idea a bit. This example only considers subclass fields.
In other words, if you have
public class SubBean extends Bean {
this example will return only fields from SubBean .
Java allows us to do this crazy:
package com.company.util; public class Bean { private int value; } package com.company.misc; public class Bean extends com.company.util.Bean { private int value; }
Not that anyone did this, but it is a problem if you want to use String as keys.
Here is the code:
import java.lang.reflect.*; import java.util.*; public final class BeanFlattener { private BeanFlattener() {} public static Map<String, Object> deepToMap(Object bean) throws IllegalAccessException { Map<String, Object> map = new LinkedHashMap<>(); putValues(bean, map, null); return map; } private static void putValues( Object bean, Map<String, Object> map, String prefix ) throws IllegalAccessException { Class<?> cls = bean.getClass(); for(Field field : cls.getDeclaredFields()) { field.setAccessible(true); Object value = field.get(bean); String key; if(prefix == null) { key = field.getName(); } else { key = prefix + "." + field.getName(); } if(isValue(value)) { map.put(key, value); } else { putValues(value, map, key); } } } private static final Set<Class<?>> valueClasses = ( Collections.unmodifiableSet(new HashSet<>(Arrays.asList( Object.class, String.class, Boolean.class, Character.class, Byte.class, Short.class, Integer.class, Long.class, Float.class, Double.class ))) ); private static boolean isValue(Object value) { return value == null || valueClasses.contains(value.getClass()); } }
Radiodef
source share