Mybatis在进行参数处理、结果映射等操做时,会涉及不少反射的操做。Mybatis源码中的对应反射模块的部分叫作Reflector.首先咱们先分清属性和字段这两个概念:函数
下面咱们就开始分析这个反射模块(注意:下面分析的源码的Mybatis的版本是3.4.6,若是有什么错误,欢迎你们在评论指出):cdn
源码图示对象
大体流程:blog
private void resolveGetterConflicts(Map> conflictingGetters) { for (Entry> entry : conflictingGetters.entrySet()) { Method winner = null; String propName = entry.getKey(); for (Method candidate : entry.getValue()) { if (winner == null) { winner = candidate; continue; } Class winnerType = winner.getReturnType(); Class candidateType = candidate.getReturnType(); if (candidateType.equals(winnerType)) { if (!boolean.class.equals(candidateType)) { throw new ReflectionException( "Illegal overloaded getter method with ambiguous type for property " + propName + " in class " + winner.getDeclaringClass() + ". This breaks the JavaBeans specification and can cause unpredictable results."); } else if (candidate.getName().startsWith("is")) { winner = candidate; } } else if (candidateType.isAssignableFrom(winnerType)) { // OK getter type is descendant } else if (winnerType.isAssignableFrom(candidateType)) { winner = candidate; } else { throw new ReflectionException( "Illegal overloaded getter method with ambiguous type for property " + propName + " in class " + winner.getDeclaringClass() + ". This breaks the JavaBeans specification and can cause unpredictable results."); } } addGetMethod(propName, winner); } }
addSetMethods() 逻辑与 addGetMethods() 差很少,我就不在重复叙述了。递归
private void addFields(Class clazz) { //获取目标class中的所有字段 Field[] fields = clazz.getDeclaredFields(); for (Field field : fields) { if (canAccessPrivateMethods()) { try { field.setAccessible(true); } catch (Exception e) { } } if (field.isAccessible()) { //判断在setmethod 中是否已经处在有这个属性了 if (!setMethods.containsKey(field.getName())) { int modifiers = field.getModifiers(); if (!(Modifier.isFinal(modifiers) && Modifier.isStatic(modifiers))) { //若是这个属性不是Final或者静态,将其添加在setmethod和settype中 addSetField(field); } } if (!getMethods.containsKey(field.getName())) { //若是这个属性不是Final或者静态,将其添加在getmethod和gettype中 addGetField(field); } } } //检查是否有父类,继续递归执行该过程 if (clazz.getSuperclass() != null) { addFields(clazz.getSuperclass()); } }