一、背景
在框架层、业务通用处理层经常会使用反射来做一些统一的处理,但是反射往往效率很低
二、解决方法
2.1 缓存
可以用ConcurrentMap懒缓存Class、Field、Method等元数据,减少ClassLoader的寻找时间
可以参考spring的ReflectionUtils
工具
/**
* Cache for {@link Class#getDeclaredMethods()} plus equivalent default methods
* from Java 8 based interfaces, allowing for fast iteration.
*/
private static final Map<Class<?>, Method[]> declaredMethodsCache = new ConcurrentReferenceHashMap<>(256);
/**
* Cache for {@link Class#getDeclaredFields()}, allowing for fast iteration.
*/
private static final Map<Class<?>, Field[]> declaredFieldsCache = new ConcurrentReferenceHashMap<>(256);
2.2 使用并行、多线程方法处理
可以借助jdk1.8的parallelStream
并行分批次处理,这种适用大批量数据处理
2.3 使用字节码技术
可以参考mapstruct
字节码技术,对存在服务生成相应处理器,寻找相应处理器进行处理,场景适用于预先知道传入类