当前位置: 首页 > 工具软件 > ReflectASM > 使用案例 >

reflectasm --反射工具

韩智明
2023-12-01
 
<!-- 反射工具 -->
<dependency>
   <groupId>org.db4j</groupId>
   <artifactId>reflectasm</artifactId>
   <version>1.11.4-2</version>
</dependency>
 
 
import com.alibaba.fastjson.JSON;
import com.ibase4jTest.core.utils.InstanceUtil;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;

/**
 * Created by Administrator on 2018/1/28.
 */
public class BaseProviderImpl implements BaseProvider, ApplicationContextAware {

    private final Logger logger = LogManager.getLogger();

    private ApplicationContext applicationContext;

    public Parameter excute(Parameter parameter) {
        logger.info("{} request :{}",parameter.getNo(), JSON.toJSONString(parameter));
        Object result =  InstanceUtil.invokeMethod(applicationContext.getBean(parameter.getService()),parameter.getMethod(),parameter.getParam());
        parameter.setResult(result);
        logger.info("{} response :{}",parameter.getNo(),JSON.toJSONString(parameter));
        return parameter;
    }

    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        this.applicationContext =applicationContext;
    }
}
 
import com.alibaba.fastjson.JSON;
import com.esotericsoftware.reflectasm.MethodAccess;
import java.beans.BeanInfo;
import java.beans.Introspector;
import java.beans.PropertyDescriptor;
import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Hashtable;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.LinkedHashSet;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;
import java.util.TreeSet;
import java.util.Vector;
import java.util.WeakHashMap;
import java.util.concurrent.ConcurrentHashMap;
import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.beanutils.PropertyUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import top.ibase4j.core.exception.DataParseException;
import top.ibase4j.core.exception.InstanceException;
import top.ibase4j.core.util.TypeParseUtil;

public final class InstanceUtil {
    protected static Logger logger = LogManager.getLogger();
    public static Map<String, Class<?>> clazzMap = new HashMap();
    public static Map<String, MethodAccess> methodMap = new HashMap();

    private InstanceUtil() {
    }

    public static final <T> T to(Object orig, Class<T> clazz) {
        Object bean = null;

        try {
            bean = clazz.newInstance();
            Class e = orig.getClass();
            BeanInfo orgInfo = Introspector.getBeanInfo(e);
            PropertyDescriptor[] orgPty = orgInfo.getPropertyDescriptors();
            HashMap propertyMap = newHashMap();
            PropertyDescriptor[] beanInfo = orgPty;
            int propertyDescriptors = orgPty.length;

            for(int var9 = 0; var9 < propertyDescriptors; ++var9) {
                PropertyDescriptor property = beanInfo[var9];
                propertyMap.put(property.getName(), property);
            }

            BeanInfo var19 = Introspector.getBeanInfo(clazz);
            PropertyDescriptor[] var20 = var19.getPropertyDescriptors();
            PropertyDescriptor[] var21 = var20;
            int var22 = var20.length;

            for(int var11 = 0; var11 < var22; ++var11) {
                PropertyDescriptor property1 = var21[var11];
                String key = property1.getName();
                if(!key.equals("class") && propertyMap.containsKey(key)) {
                    Method getter = ((PropertyDescriptor)propertyMap.get(key)).getReadMethod();
                    Method setter = property1.getWriteMethod();

                    try {
                        Object e1 = TypeParseUtil.convert(getter.invoke(orig, new Object[0]), property1.getPropertyType(), (String)null);
                        setter.invoke(bean, new Object[]{e1});
                    } catch (Exception var17) {
                        logger.error("to Error " + var17);
                    }
                }
            }
        } catch (Exception var18) {
            logger.error("to Error " + var18);
        }

        return bean;
    }

    public static final <T> T parse(String json, Class<T> clazz) {
        try {
            Map e = (Map)JSON.parseObject(json, Map.class);
            return transMap2Bean(e, clazz);
        } catch (Exception var3) {
            logger.error("parse", var3);
            return null;
        }
    }

    public static <T> T transMap2Bean(Map<String, Object> map, Class<T> clazz) {
        Object bean = null;

        try {
            bean = clazz.newInstance();
            BeanInfo e = Introspector.getBeanInfo(clazz);
            PropertyDescriptor[] propertyDescriptors = e.getPropertyDescriptors();
            PropertyDescriptor[] var5 = propertyDescriptors;
            int var6 = propertyDescriptors.length;

            for(int var7 = 0; var7 < var6; ++var7) {
                PropertyDescriptor property = var5[var7];
                String key = property.getName();
                if(map.containsKey(key)) {
                    Object value = map.get(key);
                    Method setter = property.getWriteMethod();
                    setter.invoke(bean, new Object[]{TypeParseUtil.convert(value, property.getPropertyType(), (String)null)});
                }
            }
        } catch (Exception var12) {
            logger.error("transMap2Bean Error ", var12);
        }

        return bean;
    }

    public static Map<String, Object> transBean2Map(Object obj) {
        HashMap map = newHashMap();
        if(obj == null) {
            return map;
        } else {
            try {
                BeanInfo e = Introspector.getBeanInfo(obj.getClass());
                PropertyDescriptor[] propertyDescriptors = e.getPropertyDescriptors();
                PropertyDescriptor[] var4 = propertyDescriptors;
                int var5 = propertyDescriptors.length;

                for(int var6 = 0; var6 < var5; ++var6) {
                    PropertyDescriptor property = var4[var6];
                    String key = property.getName();
                    if(!key.equals("class")) {
                        Method getter = property.getReadMethod();
                        Object value = getter.invoke(obj, new Object[0]);
                        map.put(key, value);
                    }
                }
            } catch (Exception var11) {
                logger.error("transBean2Map Error " + var11);
            }

            return map;
        }
    }

    public static <T> T getDiff(T oldBean, T newBean) {
        if(oldBean == null && newBean != null) {
            return newBean;
        } else if(newBean == null) {
            return null;
        } else {
            Class cls1 = oldBean.getClass();

            try {
                Object e = cls1.newInstance();
                BeanInfo beanInfo = Introspector.getBeanInfo(cls1);
                PropertyDescriptor[] propertyDescriptors = beanInfo.getPropertyDescriptors();
                PropertyDescriptor[] var6 = propertyDescriptors;
                int var7 = propertyDescriptors.length;

                for(int var8 = 0; var8 < var7; ++var8) {
                    PropertyDescriptor property = var6[var8];
                    String key = property.getName();
                    if(!key.equals("class")) {
                        Method getter = property.getReadMethod();
                        Method setter = property.getWriteMethod();
                        Object oldValue = getter.invoke(oldBean, new Object[0]);
                        Object newValue = getter.invoke(newBean, new Object[0]);
                        if(setter != null && newValue != null && !newValue.equals(oldValue)) {
                            setter.invoke(e, new Object[]{newValue});
                        }
                    }
                }

                return e;
            } catch (Exception var15) {
                throw new DataParseException(var15);
            }
        }
    }

    public static final Class<?> getClass(String clazz) {
        ClassLoader loader = Thread.currentThread().getContextClassLoader();

        try {
            return loader != null?Class.forName(clazz, true, loader):Class.forName(clazz);
        } catch (ClassNotFoundException var3) {
            throw new InstanceException(var3);
        }
    }

    public static final <E> List<E> getInstanceList(Class<E> cls, List<?> list) {
        ArrayList resultList = newArrayList();
        Object object = null;
        Iterator iterator = list.iterator();

        while(iterator.hasNext()) {
            Map map = (Map)iterator.next();
            object = newInstance(cls, new Object[]{map});
            resultList.add(object);
        }

        return resultList;
    }

    public static final <E> List<E> getInstanceList(Class<E> cls, ResultSet rs) {
        ArrayList resultList = newArrayList();

        try {
            Object e = cls.newInstance();
            Field[] fields = cls.getDeclaredFields();

            while(rs.next()) {
                e = cls.newInstance();

                for(int i = 0; i < fields.length; ++i) {
                    String fieldName = fields[i].getName();
                    PropertyUtils.setProperty(e, fieldName, rs.getObject(fieldName));
                }

                resultList.add(e);
            }

            return resultList;
        } catch (Exception var7) {
            throw new InstanceException(var7);
        }
    }

    public static final <E> E newInstance(Class<E> cls, Map<String, ?> map) {
        Object object = null;

        try {
            object = cls.newInstance();
            BeanUtils.populate(object, map);
            return object;
        } catch (Exception var4) {
            throw new InstanceException(var4);
        }
    }

    public static final Object newInstance(String clazz) {
        try {
            return getClass(clazz).newInstance();
        } catch (Exception var2) {
            throw new InstanceException(var2);
        }
    }

    public static final <K> K newInstance(Class<K> cls, Object... args) {
        try {
            Class[] e = null;
            if(args != null) {
                e = new Class[args.length];
                int cons = 0;

                for(int j = args.length; cons < j; ++cons) {
                    e[cons] = args[cons].getClass();
                }
            }

            Constructor var6 = cls.getConstructor(e);
            return var6.newInstance(args);
        } catch (Exception var5) {
            throw new InstanceException(var5);
        }
    }

    public static final Object newInstance(String className, Object... args) {
        try {
            Class e = (Class)clazzMap.get(className);
            if(e == null) {
                e = Class.forName(className);
                clazzMap.put(className, e);
            }

            return newInstance(e, args);
        } catch (Exception var3) {
            throw new InstanceException(var3);
        }
    }

    public static final Object invokeMethod(Object owner, String methodName, Object... args) {
        Class ownerClass = owner.getClass();
        String key = null;
        if(args != null) {
            Class[] methodAccess = new Class[args.length];
            int i = 0;

            for(int j = args.length; i < j; ++i) {
                if(args[i] != null) {
                    methodAccess[i] = args[i].getClass();
                }
            }

            key = ownerClass + "_" + methodName + "_" + StringUtils.join(methodAccess, ",");
        } else {
            key = ownerClass + "_" + methodName;
        }

        MethodAccess var8 = (MethodAccess)methodMap.get(key);
        if(var8 == null) {
            var8 = MethodAccess.get(ownerClass);
            methodMap.put(key, var8);
        }

        return var8.invoke(owner, methodName, args);
    }

    public static final <E> ArrayList<E> newArrayList() {
        return new ArrayList();
    }

    public static final <E> ArrayList<E> newArrayList(E... e) {
        ArrayList list = new ArrayList();
        Collections.addAll(list, e);
        return list;
    }

    public static final <k, v> HashMap<k, v> newHashMap() {
        return new HashMap();
    }

    public static final <E> HashSet<E> newHashSet() {
        return new HashSet();
    }

    public static final <k, v> Hashtable<k, v> newHashtable() {
        return new Hashtable();
    }

    public static final <k, v> LinkedHashMap<k, v> newLinkedHashMap() {
        return new LinkedHashMap();
    }

    public static final <E> LinkedHashSet<E> newLinkedHashSet() {
        return new LinkedHashSet();
    }

    public static final <E> LinkedList<E> newLinkedList() {
        return new LinkedList();
    }

    public static final <k, v> TreeMap<k, v> newTreeMap() {
        return new TreeMap();
    }

    public static final <E> TreeSet<E> newTreeSet() {
        return new TreeSet();
    }

    public static final <E> Vector<E> newVector() {
        return new Vector();
    }

    public static final <k, v> WeakHashMap<k, v> newWeakHashMap() {
        return new WeakHashMap();
    }

    public static final <k, v> HashMap<k, v> newHashMap(k key, v value) {
        HashMap map = newHashMap();
        map.put(key, value);
        return map;
    }

    public static final <k, v> LinkedHashMap<k, v> newLinkedHashMap(k key, v value) {
        LinkedHashMap map = newLinkedHashMap();
        map.put(key, value);
        return map;
    }

    public static final <k, v> ConcurrentHashMap<k, v> newConcurrentHashMap() {
        return new ConcurrentHashMap();
    }
}

 类似资料: