主函数是argNamesOfMatchingConstructor。 其功能主要是获取参数名。
private List<String> argNamesOfMatchingConstructor(List<String> constructorArgNames) { // 获取声明的构造方法 Constructor<?>[] constructors = resultMap.type.getDeclaredConstructors(); // 遍历每个构造方法 for (Constructor<?> constructor : constructors) { // 获取构造方法的参数类型 Class<?>[] paramTypes = constructor.getParameterTypes(); // 参数长度和获取到参数类型数量一致 if (constructorArgNames.size() == paramTypes.length) { // 获取构造函数的参数名称 List<String> paramNames = getArgNames(constructor); if (constructorArgNames.containsAll(paramNames) && argTypesMatch(constructorArgNames, paramTypes, paramNames)) { return paramNames; } } } return null; }getArgNames获取构造函数的参数名
private List<String> getArgNames(Constructor<?> constructor) { List<String> paramNames = new ArrayList<>(); List<String> actualParamNames = null; // 获取参数的注解 final Annotation[][] paramAnnotations = constructor.getParameterAnnotations(); int paramCount = paramAnnotations.length; for (int paramIndex = 0; paramIndex < paramCount; paramIndex++) { String name = null; for (Annotation annotation : paramAnnotations[paramIndex]) { if (annotation instanceof Param) { name = ((Param) annotation).value(); break; } } if (name == null && resultMap.configuration.isUseActualParamName()) { if (actualParamNames == null) { actualParamNames = ParamNameUtil.getParamNames(constructor); } if (actualParamNames.size() > paramIndex) { name = actualParamNames.get(paramIndex); } } paramNames.add(name != null ? name : "arg" + paramIndex); } return paramNames; } }argTypesMatch方法用来检查构造方法参数是否匹配
private boolean argTypesMatch(final List<String> constructorArgNames, Class<?>[] paramTypes, List<String> paramNames) { for (int i = 0; i < constructorArgNames.size(); i++) { Class<?> actualType = paramTypes[paramNames.indexOf(constructorArgNames.get(i))]; Class<?> specifiedType = resultMap.constructorResultMappings.get(i).getJavaType(); if (!actualType.equals(specifiedType)) { if (log.isDebugEnabled()) { log.debug("While building result map '" + resultMap.id + "', found a constructor with arg names " + constructorArgNames + ", but the type of '" + constructorArgNames.get(i) + "' did not match. Specified: [" + specifiedType.getName() + "] Declared: [" + actualType.getName() + "]"); } return false; } } return true; }