源码中一些好的代码写法
1 Map相关
摘自 Spring中加载 META-INF/spring.factories 下的类名,Map的巧初始化:
Map<String, List<String>> result = cache.get(classLoader); // 缓存中有就直接返回 if (result != null) { return result; } // 初始化Map result = new HashMap<>(); // value是个集合,初始化value并放数据 result.computeIfAbsent(factoryTypeName, key -> new ArrayList<>()).add(factoryImplementationName.trim()); // 也可以这么写 result.putIfAbsent(factoryTypeName, new ArrayList<>()).add(factoryImplementationName.trim()); // 对value去重并转换为可读集合 result.replaceAll((factoryType, implementations) -> implementations.stream().distinct().collect(Collectors.collectingAndThen(Collectors.toList(), Collections::unmodifiableList)));
2 字符串相关
摘自 Spring中加载 META-INF/spring.factories 下的类名,逗号分隔:
// 逗号分隔出来每个全类名 String[] factoryImplementationNames = StringUtils.commaDelimitedListToStringArray((String) entry.getValue());
3 对象相关
对象比较 ObjectUtils.nullSafeEquals(this.sourceType, otherKey.sourceType)); public static boolean nullSafeEquals(@Nullable Object o1, @Nullable Object o2) { if (o1 == o2) { return true; } if (o1 == null || o2 == null) { return false; } if (o1.equals(o2)) { return true; } if (o1.getClass().isArray() && o2.getClass().isArray()) { return arrayEquals(o1, o2); } return false; }
4 写法相关
4.1 标志移除
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
public <T> void addMapper(Class<T> type) { if (type.isInterface()) { if (hasMapper(type)) { throw new BindingException("Type " + type + " is already known to the MapperRegistry."); } boolean loadCompleted = false; try { /* * 将 type 和 MapperProxyFactory 进行绑定, * MapperProxyFactory 来为 mapper 接口生成代理类 */ knownMappers.put(type, new MapperProxyFactory<>(type)); // It's important that the type is added before the parser is run // otherwise the binding may automatically be attempted by the // mapper parser. If the type is already known, it won't try. // 创建注解解析器。在 MyBatis 中,有 XML 和 注解两种配置方式可选 MapperAnnotationBuilder parser = new MapperAnnotationBuilder(config, type); // 解析注解中的信息 parser.parse(); loadCompleted = true; } finally { if (!loadCompleted) { knownMappers.remove(type); } } } }
private final Map<Class<?>, MapperProxyFactory<?>> knownMappers = new HashMap<>(); public <T> void addMapper(Class<T> type) { if (type.isInterface()) { if (hasMapper(type)) { throw new BindingException("Type " + type + " is already known to the MapperRegistry."); } boolean loadCompleted = false; try { // 业务操作 loadCompleted = true; } finally { if (!loadCompleted) { knownMappers.remove(type); } } } }