在阅读mybatis拦截器链源代码时,发现其是这么写的:
//
// Source code recreated from a .class file by IntelliJ IDEA
// (powered by FernFlower decompiler)
//
package org.apache.ibatis.plugin;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;
// mybatis拦截器链
public class InterceptorChain {
// final修饰 interceptors,位于堆内存,引用地址不可改变
private final List<Interceptor> interceptors = new ArrayList();
public InterceptorChain() {
}
public Object pluginAll(Object target) {
Interceptor interceptor;
for(Iterator var2 = this.interceptors.iterator(); var2.hasNext(); target = interceptor.plugin(target)) {
interceptor = (Interceptor)var2.next();
}
return target;
}
// 添加拦截器
public void addInterceptor(Interceptor interceptor) {
this.interceptors.add(interceptor);
}
// 返回一个不可修改的(准确来说,是可以添加,上面有个addInterceptor方法,但是不可以删除)list集合
public List<Interceptor> getInterceptors() {
return Collections.unmodifiableList(this.interceptors);
}
}
Collections.unmodifiableList使用场景:
当我们需要一个不可变集合,不仅指向该集合的引用地址不可变动,集合内的元素也不可改变。
参考上述代码,去除addInterceptor,就可以做到彻底不可改变。
本文详细分析了MyBatis拦截器链的源代码,特别是`InterceptorChain`类中如何使用不可变集合`Collections.unmodifiableList`确保拦截器列表在运行时的稳定性和安全性。通过移除`addInterceptor`方法,可以实现完全不可变的拦截器列表。同时,文章探讨了不可变集合在防止意外修改集合内容方面的关键作用。
922

被折叠的 条评论
为什么被折叠?



