Collections.unmodifiableList方法

 在读mybatis源码时,发现其拦截器链是这么写的:

package org.apache.ibatis.plugin;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

/**
 * @author Clinton Begin
 */
public class InterceptorChain {
  
  //final标识interceptors 引用不可变
  private final List<Interceptor> interceptors = new ArrayList<Interceptor>();

  public Object pluginAll(Object target) {
    for (Interceptor interceptor : interceptors) {
      target = interceptor.plugin(target);
    }
    return target;
  }

  //可以添加拦截器
  public void addInterceptor(Interceptor interceptor) {
    interceptors.add(interceptor);
  }
  
  //返回一个不可修改(准确的说,上边有个addInterceptor()方法可以添加,但是不可删除)的列表
  public List<Interceptor> getInterceptors() {
    return Collections.unmodifiableList(interceptors);
  }

}

Collections.unmodifiableList方法平时用的不多,如果有类似的场景需求:持有一个不可变的集合,不仅指向该集合的引用不可变,集合内的元素也不可变,参考以上的代码,把add方法去掉以后,就可以做到彻底不可变。可以参考如下:

/**  
* <p>Title: Test</p>  
* <p>Description: </p>  
* @author wangzhj 
* @date 2020年1月11日  
*/
public class Test {
    
    private static final List<String> interceptors = new ArrayList<String>();

    static{
      interceptors.add("1");
      interceptors.add("2");
    }
    
    public static List<String> getInterceptors() {
      return Collections.unmodifiableList(interceptors);
    }
    
    /**  
     * <p>Title: main</p>  
     * <p>Description: </p>  
     * @param args  
     */
    public static void main(String[] args) {
          //抛出异常lang.UnsupportedOperationException
//        Test.getInterceptors().add("c");
        
        Test.getInterceptors().forEach(System.out::println);
    }

}

 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值