源码中一些好的代码写法
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 标志移除

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); } } } }
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 分享4款.NET开源、免费、实用的商城系统
· 全程不用写代码,我用AI程序员写了一个飞机大战
· Obsidian + DeepSeek:免费 AI 助力你的知识管理,让你的笔记飞起来!
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了