java entity object and conversion tools between the Map (and have not yet see)

Conversion between the tools and the entity object java Map

import java.lang.reflect.Field;
import java.util.HashMap;
import java.util.Map;
 
public class EntityUtils {
    /**
     * 实体类转Map
     * @param object
     * @return
     */
    public static Map<String, Object> entityToMap(Object object) {
        Map<String, Object> map = new HashMap();
        for (Field field : object.getClass().getDeclaredFields()){
            try {
                boolean flag = field.isAccessible();
                field.setAccessible ( to true ); 
                Object O = Field.get (Object); 
                map.put (field.getName (), O); 
                field.setAccessible (In Flag); 
            } the catch (Exception E) { 
                e.printStackTrace (); 
            } 
        } 
        return the Map; 
    } 
    
    / ** 
     * the Map transferred entity class 
     * @param the Map to initialized data, key fields must be the same as the name of the entity and the members of the class, or else assign null 
     * @param the entity need to be converted into an entity class 
     * @ return 
     * / 
    public  static <T> T mapToEntity (the Map <String, Object> Map, Class <T> Entity) { 
        T T= null;
        try {
            t = entity.newInstance();
            for(Field field : entity.getDeclaredFields()) {
                if (map.containsKey(field.getName())) {
                    boolean flag = field.isAccessible();
                    field.setAccessible(true);
                    Object object = map.get(field.getName());
                    if (object!= null && field.getType().isAssignableFrom(object.getClass())) {
                         field.set(t, object);
                    }
                    field.setAccessible(flag);
                }
            }
            return t;
        } catch (InstantiationException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return t;
    }
}

Guess you like

Origin www.cnblogs.com/zouhong/p/12091560.html