业务场景 :如果某个表某些字段被修改,然后就要重新计算另外一个表的数据(为什么要用集合,因为查数据库性能太慢,如果a表某些字段被修改,b表可能要修改几百条数据,所以修改前,要找出符合触发条件的记录)
package list;
import org.apache.commons.beanutils.BeanUtils;
import org.springframework.cglib.proxy.Enhancer;
import org.springframework.cglib.proxy.MethodInterceptor;
import org.springframework.cglib.proxy.MethodProxy;
import java.lang.reflect.Method;
import java.lang.reflect.ParameterizedType;
import java.util.*;
import java.util.function.Consumer;
public abstract class ObjectInterceptUtil<T>{
private static final Enhancer enhancer = new Enhancer();
private Class<T> clazz;
private List<T> source;
private List<T> target;
private boolean flag; //开关
private ObjectInterceptUtil<T> build(List<T> s, List<T> t, Consumer<List> c, String... f) {
this.clazz=(Class<T>)((ParameterizedType)getClass().getGenericSuperclass()).getActualTypeArguments()[0];
this.flag = false;
this.source = s;
this.target = t;
enhancer.setSuperclass(clazz);
enhancer.setCallback(new ObjectMethodInterceptor(c, Arrays.asList(f)));
return this;
}
public ObjectInterceptUtil<T> build(List<T> s, List<T> t, Consumer<List> c) {
return build(s, t, c, "");
}
public ObjectInterceptUtil<T> build(List<T> s, List<T> t, String... f) {
return build(s, t, null, f);
}
public ObjectInterceptUtil<T> ok() {
if (Objects.isNull(source)) {
return null;
}
Iterator<T> iterator = source.iterator();
if (iterator.hasNext()) {
T next = iterator.next();
source.remove(next);
source.add(0, apply(next));
}
Collections.reverse(source);
this.flag = true;
return this;
}
private T apply(T ele) {
try {
T create = (T) enhancer.create();
BeanUtils.copyProperties(create, ele);
return create;
} catch (Exception e) {
e.printStackTrace();
return ele;
}
}
class ObjectMethodInterceptor<T> implements MethodInterceptor {
private Consumer consumer;
private List<String> fields;
public ObjectMethodInterceptor(Consumer<List> c, List<String> f) {
this.consumer = c;
this.fields = f;
}
private String lowercaseFirst(String s){
char[] chars = s.toCharArray();
chars[0] = Character.toLowerCase(chars[0]);
return String.valueOf(chars);
}
@Override
public Object intercept(Object o, Method method, Object[] args, MethodProxy methodProxy) throws Throwable {
String field = lowercaseFirst(method.getName().replace("set", ""));
if (!Objects.isNull(consumer) && flag) {//提供后续自定义扩展
consumer.accept(Arrays.asList(o, method, args, methodProxy, source, target));
} else if (fields.contains(field.trim()) && flag) {
ObjectInterceptUtil.this.source.remove(o);
((List<T>) ObjectInterceptUtil.this.target).add((T) o);
}
return methodProxy.invokeSuper(o, args);
}
}
}