List<对象> list 转换为 List<Map<String,Object>>时候 需要进行字段映射转换


前言

有时候需要将List<对象> list 转换为 List<Map<String,Object>>时候 需要进行字段映射转换


1.转换代码

代码如下(示例):

public Map<?, ?> objectToMap(Object obj) {
        if (obj == null) {
            return null;
        }
        return new org.apache.commons.beanutils.BeanMap(obj);
    }
//
// Source code recreated from a .class file by IntelliJ IDEA
// (powered by FernFlower decompiler)
//

package org.apache.commons.beanutils;

import java.beans.BeanInfo;
import java.beans.IntrospectionException;
import java.beans.Introspector;
import java.beans.PropertyDescriptor;
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.AbstractMap;
import java.util.AbstractSet;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
import org.apache.commons.collections.Transformer;
import org.apache.commons.collections.keyvalue.AbstractMapEntry;

public class BeanMap extends AbstractMap<Object, Object> implements Cloneable {
    private transient Object bean;
    private transient HashMap<String, Method> readMethods = new HashMap();
    private transient HashMap<String, Method> writeMethods = new HashMap();
    private transient HashMap<String, Class<? extends Object>> types = new HashMap();
    public static final Object[] NULL_ARGUMENTS = new Object[0];
    private static final Map<Class<? extends Object>, Transformer> typeTransformers = Collections.unmodifiableMap(createTypeTransformers());
    /** @deprecated */
    @Deprecated
    public static HashMap defaultTransformers = new HashMap() {
        public void clear() {
            throw new UnsupportedOperationException();
        }

        public boolean containsKey(Object key) {
            return BeanMap.typeTransformers.containsKey(key);
        }

        public boolean containsValue(Object value) {
            return BeanMap.typeTransformers.containsValue(value);
        }

        public Set entrySet() {
            return BeanMap.typeTransformers.entrySet();
        }

        public Object get(Object key) {
            return BeanMap.typeTransformers.get(key);
        }

        public boolean isEmpty() {
            return false;
        }

        public Set keySet() {
            return BeanMap.typeTransformers.keySet();
        }

        public Object put(Object key, Object value) {
            throw new UnsupportedOperationException();
        }

        public void putAll(Map m) {
            throw new UnsupportedOperationException();
        }

        public Object remove(Object key) {
            throw new UnsupportedOperationException();
        }

        public int size() {
            return BeanMap.typeTransformers.size();
        }

        public Collection values() {
            return BeanMap.typeTransformers.values();
        }
    };

    private static Map<Class<? extends Object>, Transformer> createTypeTransformers() {
        Map<Class<? extends Object>, Transformer> defaultTransformers = new HashMap();
        defaultTransformers.put(Boolean.TYPE, new Transformer() {
            public Object transform(Object input) {
                return Boolean.valueOf(input.toString());
            }
        });
        defaultTransformers.put(Character.TYPE, new Transformer() {
            public Object transform(Object input) {
                return new Character(input.toString().charAt(0));
            }
        });
        defaultTransformers.put(Byte.TYPE, new Transformer() {
            public Object transform(Object input) {
                return Byte.valueOf(input.toString());
            }
        });
        defaultTransformers.put(Short.TYPE, new Transformer() {
            public Object transform(Object input) {
                return Short.valueOf(input.toString());
            }
        });
        defaultTransformers.put(Integer.TYPE, new Transformer() {
            public Object transform(Object input) {
                return Integer.valueOf(input.toString());
            }
        });
        defaultTransformers.put(Long.TYPE, new Transformer() {
            public Object transform(Object input) {
                return Long.valueOf(input.toString());
            }
        });
        defaultTransformers.put(Float.TYPE, new Transformer() {
            public Object transform(Object input) {
                return Float.valueOf(input.toString());
            }
        });
        defaultTransformers.put(Double.TYPE, new Transformer() {
            public Object transform(Object input) {
                return Double.valueOf(input.toString());
            }
        });
        return defaultTransformers;
    }

    public BeanMap() {
    }

    public BeanMap(Object bean) {
        this.bean = bean;
        this.initialise();
    }

    public String toString() {
        return "BeanMap<" + String.valueOf(this.bean) + ">";
    }

    public Object clone() throws CloneNotSupportedException {
        BeanMap newMap = (BeanMap)super.clone();
        if (this.bean == null) {
            return newMap;
        } else {
            Object newBean = null;
            Class beanClass = this.bean.getClass();

            CloneNotSupportedException cnse;
            try {
                newBean = beanClass.newInstance();
            } catch (Exception var8) {
                cnse = new CloneNotSupportedException("Unable to instantiate the underlying bean \"" + beanClass.getName() + "\": " + var8);
                BeanUtils.initCause(cnse, var8);
                throw cnse;
            }

            try {
                newMap.setBean(newBean);
            } catch (Exception var7) {
                cnse = new CloneNotSupportedException("Unable to set bean in the cloned bean map: " + var7);
                BeanUtils.initCause(cnse, var7);
                throw cnse;
            }

            try {
                Iterator readableKeys = this.readMethods.keySet().iterator();

                while(readableKeys.hasNext()) {
                    Object key = readableKeys.next();
                    if (this.getWriteMethod(key) != null) {
                        newMap.put(key, this.get(key));
                    }
                }

                return newMap;
            } catch (Exception var6) {
                cnse = new CloneNotSupportedException("Unable to copy bean values to cloned bean map: " + var6);
                BeanUtils.initCause(cnse, var6);
                throw cnse;
            }
        }
    }

    public void putAllWriteable(BeanMap map) {
        Iterator readableKeys = map.readMethods.keySet().iterator();

        while(readableKeys.hasNext()) {
            Object key = readableKeys.next();
            if (this.getWriteMethod(key) != null) {
                this.put(key, map.get(key));
            }
        }

    }

    public void clear() {
        if (this.bean != null) {
            Class beanClass = null;

            try {
                beanClass = this.bean.getClass();
                this.bean = beanClass.newInstance();
            } catch (Exception var4) {
                UnsupportedOperationException uoe = new UnsupportedOperationException("Could not create new instance of class: " + beanClass);
                BeanUtils.initCause(uoe, var4);
                throw uoe;
            }
        }
    }

    public boolean containsKey(Object name) {
        Method method = this.getReadMethod(name);
        return method != null;
    }

    public boolean containsValue(Object value) {
        return super.containsValue(value);
    }

    public Object get(Object name) {
        if (this.bean != null) {
            Method method = this.getReadMethod(name);
            if (method != null) {
                try {
                    return method.invoke(this.bean, NULL_ARGUMENTS);
                } catch (IllegalAccessException var4) {
                    this.logWarn(var4);
                } catch (IllegalArgumentException var5) {
                    this.logWarn(var5);
                } catch (InvocationTargetException var6) {
                    this.logWarn(var6);
                } catch (NullPointerException var7) {
                    this.logWarn(var7);
                }
            }
        }

        return null;
    }

    public Object put(Object name, Object value) throws IllegalArgumentException, ClassCastException {
        if (this.bean == null) {
            return null;
        } else {
            Object oldValue = this.get(name);
            Method method = this.getWriteMethod(name);
            if (method == null) {
                throw new IllegalArgumentException("The bean of type: " + this.bean.getClass().getName() + " has no property called: " + name);
            } else {
                IllegalArgumentException iae;
                try {
                    Object[] arguments = this.createWriteMethodArguments(method, value);
                    method.invoke(this.bean, arguments);
                    Object newValue = this.get(name);
                    this.firePropertyChange(name, oldValue, newValue);
                    return oldValue;
                } catch (InvocationTargetException var7) {
                    iae = new IllegalArgumentException(var7.getMessage());
                    if (!BeanUtils.initCause(iae, var7)) {
                        this.logInfo(var7);
                    }

                    throw iae;
                } catch (IllegalAccessException var8) {
                    iae = new IllegalArgumentException(var8.getMessage());
                    if (!BeanUtils.initCause(iae, var8)) {
                        this.logInfo(var8);
                    }

                    throw iae;
                }
            }
        }
    }

    public int size() {
        return this.readMethods.size();
    }

    public Set<Object> keySet() {
        return Collections.unmodifiableSet(this.readMethods.keySet());
    }

    public Set<java.util.Map.Entry<Object, Object>> entrySet() {
        return Collections.unmodifiableSet(new AbstractSet<java.util.Map.Entry<Object, Object>>() {
            public Iterator<java.util.Map.Entry<Object, Object>> iterator() {
                return BeanMap.this.entryIterator();
            }

            public int size() {
                return BeanMap.this.readMethods.size();
            }
        });
    }

    public Collection<Object> values() {
        ArrayList<Object> answer = new ArrayList(this.readMethods.size());
        Iterator iter = this.valueIterator();

        while(iter.hasNext()) {
            answer.add(iter.next());
        }

        return Collections.unmodifiableList(answer);
    }

    public Class<?> getType(String name) {
        return (Class)this.types.get(name);
    }

    public Iterator<String> keyIterator() {
        return this.readMethods.keySet().iterator();
    }

    public Iterator<Object> valueIterator() {
        final Iterator<?> iter = this.keyIterator();
        return new Iterator<Object>() {
            public boolean hasNext() {
                return iter.hasNext();
            }

            public Object next() {
                Object key = iter.next();
                return BeanMap.this.get(key);
            }

            public void remove() {
                throw new UnsupportedOperationException("remove() not supported for BeanMap");
            }
        };
    }

    public Iterator<java.util.Map.Entry<Object, Object>> entryIterator() {
        final Iterator<String> iter = this.keyIterator();
        return new Iterator<java.util.Map.Entry<Object, Object>>() {
            public boolean hasNext() {
                return iter.hasNext();
            }

            public java.util.Map.Entry<Object, Object> next() {
                Object key = iter.next();
                Object value = BeanMap.this.get(key);
                java.util.Map.Entry<Object, Object> tmpEntry = new BeanMap.Entry(BeanMap.this, key, value);
                return tmpEntry;
            }

            public void remove() {
                throw new UnsupportedOperationException("remove() not supported for BeanMap");
            }
        };
    }

    public Object getBean() {
        return this.bean;
    }

    public void setBean(Object newBean) {
        this.bean = newBean;
        this.reinitialise();
    }

    public Method getReadMethod(String name) {
        return (Method)this.readMethods.get(name);
    }

    public Method getWriteMethod(String name) {
        return (Method)this.writeMethods.get(name);
    }

    protected Method getReadMethod(Object name) {
        return (Method)this.readMethods.get(name);
    }

    protected Method getWriteMethod(Object name) {
        return (Method)this.writeMethods.get(name);
    }

    protected void reinitialise() {
        this.readMethods.clear();
        this.writeMethods.clear();
        this.types.clear();
        this.initialise();
    }

    private void initialise() {
        if (this.getBean() != null) {
            Class beanClass = this.getBean().getClass();

            try {
                BeanInfo beanInfo = Introspector.getBeanInfo(beanClass);
                PropertyDescriptor[] propertyDescriptors = beanInfo.getPropertyDescriptors();
                if (propertyDescriptors != null) {
                    for(int i = 0; i < propertyDescriptors.length; ++i) {
                        PropertyDescriptor propertyDescriptor = propertyDescriptors[i];
                        if (propertyDescriptor != null) {
                            String name = propertyDescriptor.getName();
                            Method readMethod = propertyDescriptor.getReadMethod();
                            Method writeMethod = propertyDescriptor.getWriteMethod();
                            Class<? extends Object> aType = propertyDescriptor.getPropertyType();
                            if (readMethod != null) {
                                this.readMethods.put(name, readMethod);
                            }

                            if (writeMethod != null) {
                                this.writeMethods.put(name, writeMethod);
                            }

                            this.types.put(name, aType);
                        }
                    }
                }
            } catch (IntrospectionException var10) {
                this.logWarn(var10);
            }

        }
    }

    protected void firePropertyChange(Object key, Object oldValue, Object newValue) {
    }

    protected Object[] createWriteMethodArguments(Method method, Object value) throws IllegalAccessException, ClassCastException {
        IllegalArgumentException iae;
        try {
            if (value != null) {
                Class<? extends Object>[] types = method.getParameterTypes();
                if (types != null && types.length > 0) {
                    Class<? extends Object> paramType = types[0];
                    if (!paramType.isAssignableFrom(value.getClass())) {
                        value = this.convertType(paramType, value);
                    }
                }
            }

            Object[] answer = new Object[]{value};
            return answer;
        } catch (InvocationTargetException var5) {
            iae = new IllegalArgumentException(var5.getMessage());
            if (!BeanUtils.initCause(iae, var5)) {
                this.logInfo(var5);
            }

            throw iae;
        } catch (InstantiationException var6) {
            iae = new IllegalArgumentException(var6.getMessage());
            if (!BeanUtils.initCause(iae, var6)) {
                this.logInfo(var6);
            }

            BeanUtils.initCause(iae, var6);
            throw iae;
        }
    }

    protected Object convertType(Class<?> newType, Object value) throws InstantiationException, IllegalAccessException, IllegalArgumentException, InvocationTargetException {
        Class[] types = new Class[]{value.getClass()};

        try {
            Constructor<?> constructor = newType.getConstructor(types);
            Object[] arguments = new Object[]{value};
            return constructor.newInstance(arguments);
        } catch (NoSuchMethodException var6) {
            Transformer transformer = this.getTypeTransformer(newType);
            return transformer != null ? transformer.transform(value) : value;
        }
    }

    protected Transformer getTypeTransformer(Class<?> aType) {
        return (Transformer)typeTransformers.get(aType);
    }

    protected void logInfo(Exception ex) {
        System.out.println("INFO: Exception: " + ex);
    }

    protected void logWarn(Exception ex) {
        System.out.println("WARN: Exception: " + ex);
        ex.printStackTrace();
    }

    protected static class Entry extends AbstractMapEntry {
        private final BeanMap owner;

        protected Entry(BeanMap owner, Object key, Object value) {
            super(key, value);
            this.owner = owner;
        }

        public Object setValue(Object value) {
            Object key = this.getKey();
            Object oldValue = this.owner.get(key);
            this.owner.put(key, value);
            Object newValue = this.owner.get(key);
            super.setValue(newValue);
            return oldValue;
        }
    }
}


总结

长文件复制作为工具类,代码中直接调用第一条代码块方法即可

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值