0
点赞
收藏
分享

微信扫一扫

Collections.unmodifiableList方法

在阅读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,就可以做到彻底不可改变。


举报

相关推荐

0 条评论