Mybatis3.5.1源码分析
- Mybatis-SqlSessionFactoryBuilder,XMLConfigBuilder,XPathParser源码解析
- Mybatis-Configuration源码解析
- Mybatis-事务对象源码解析
- Mybatis-数据源源码解析
- Mybatis缓存策略源码解析
- Mybatis-DatabaseIdProvider源码解析
- Mybatis-TypeHandler源码解析
- Mybatis-Reflector源码解析
- Mybatis-ObjectFactory,ObjectWrapperFactory源码分析
- Mybatis-Mapper各类标签封装类源码解析
- Mybatis-XMLMapperBuilder,XMLStatmentBuilder源码分析
- Mybatis-MapperAnnotationBuilder源码分析
- [Mybatis-MetaObject,MetaClass源码解析]https://www.jianshu.com/p/f51fa552f30a)
- Mybatis-LanguageDriver源码解析
- Mybatis-SqlSource源码解析
- Mybatis-SqlNode源码解析
- Mybatis-KeyGenerator源码解析
- Mybatis-Executor源码解析
- Mybatis-ParameterHandler源码解析
- Mybatis-StatementHandler源码解析
- Mybatis-DefaultResultSetHandler(一)源码解析
- Mybatis-DefaultResultSetHandler(二)源码解析
- Mybatis-ResultHandler,Cursor,RowBounds 源码分析
- Mybatis-MapperProxy源码解析
- Mybatis-SqlSession源码解析
- Mybatis-Interceptor源码解析
ReflectorFactory
/**
* Copyright 2009-2015 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.ibatis.reflection;
/**
* 反射信息类工厂
*/
public interface ReflectorFactory {
/**
* 是否会缓存Reflector对象
*/
boolean isClassCacheEnabled();
/**
* 设置是否缓存Reflector对象
*/
void setClassCacheEnabled(boolean classCacheEnabled);
/**
* 查找type对应的Refector,没有则new一个Refector并设置进去缓存Map中。
*/
Reflector findForClass(Class> type);
}
DefaultReflectorFactory
/**
* Copyright 2009-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.ibatis.reflection;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
/**
* 默认反射器工厂
*/
public class DefaultReflectorFactory implements ReflectorFactory {
/**
* 类缓存启用
*/
private boolean classCacheEnabled = true;
/**
* 反射信息类对象 映射缓存集合
*/
private final ConcurrentMap, Reflector> reflectorMap = new ConcurrentHashMap<>();
public DefaultReflectorFactory() {
}
/**
* 类缓存启用
*/
@Override
public boolean isClassCacheEnabled() {
return classCacheEnabled;
}
/**
* 类缓存启用
*/
@Override
public void setClassCacheEnabled(boolean classCacheEnabled) {
this.classCacheEnabled = classCacheEnabled;
}
/**
* 获取 {@code type} 的反射信息类对象
* @param type 类
* @return
*/
@Override
public Reflector findForClass(Class> type) {
//如果启用了缓存
if (classCacheEnabled) {
// synchronized (type) removed see issue #461
//从refletMap获取type对应的Reflector,如果没有,就新建一个
return reflectorMap.computeIfAbsent(type, Reflector::new);
} else {
//新建一个反射信息类对象
return new Reflector(type);
}
}
}
Reflector
/**
* Copyright 2009-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.ibatis.reflection;
import java.lang.reflect.Array;
import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.GenericArrayType;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.ReflectPermission;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Map.Entry;
import org.apache.ibatis.reflection.invoker.GetFieldInvoker;
import org.apache.ibatis.reflection.invoker.Invoker;
import org.apache.ibatis.reflection.invoker.MethodInvoker;
import org.apache.ibatis.reflection.invoker.SetFieldInvoker;
import org.apache.ibatis.reflection.property.PropertyNamer;
/**
* This class represents a cached set of class definition information that
* allows for easy mapping between property names and getter/setter methods.
* 反射信息类。能在这里更加便捷的拿到其类的属性,getter,setter,setter参数类型,getter的返回类型等。
* 值得注意的地方,该类整理的属性名并不是从类中直接getDeclaredField方法,或者是getField方法中获取
* 而是从getter,setter方法名中解析拼装出来的,这一点使得POJO的扩展性提高很多,比如,我并没有在类中定义一个order的属性,
* 但是我加上了其getOrder或setOrder方法,Reflector还是会认为有一个order属性在你定义的类中
* 参照博客:https://www.cnblogs.com/nizuimeiabc1/p/9844247.html
* @author Clinton Begin
*
*/
public class Reflector {
/**
* 对应的Class 类型,当前类
*/
private final Class> type;
/**
* 可读属性的名称集合,可读属性就是存在相应getter 方法的属性,初始值为空数纽
*/
private final String[] readablePropertyNames;
/**
* 可写属性的名称集合,可写属性就是存在相应setter 方法的属性,初始值为空数纽
*/
private final String[] writablePropertyNames;
/**
* 属性相应的setter 方法, key 是属性名称, value 是Invoker 对象,它是对setter 方法对应
*/
private final Map setMethods = new HashMap<>();
/**
* 属性相应的getter 方法, key 是属性名称, value 是Invoker 对象,它是对setter 方法对应
*/
private final Map getMethods = new HashMap<>();
/**
* 属性相应的setter 方法的参数值类型, ke y 是属性名称, value 是setter 方法的参数类型
*/
private final Map> setTypes = new HashMap<>();
/**
* 属性相应的getter 方法的返回位类型, key 是属性名称, value 是getter 方法的返回位类型
*/
private final Map> getTypes = new HashMap<>();
/**
* 默认构造方法,无参构造方法
*/
private Constructor> defaultConstructor;
/**
* 所有属性名称的集合(不分大小写),key=属性名去大写,value=类中真正的属性名,
* 这里通过设置key全部大小,能够保证就算写得再烂的驼峰命名,可以拿到正确的属性。
*/
private Map caseInsensitivePropertyMap = new HashMap<>();
public Reflector(Class> clazz) {
type = clazz;
//查找clazz的无参构造方法,通过反射遍历所有构造方法,找到构造参数集合长度为0的。
addDefaultConstructor(clazz);
//处理clazz 中的getter 方法,填充getMethods 集合和getTypes 集合
addGetMethods(clazz);
//处理clazz 中的set ter 方法,填充setMethods 集合和set Types 集合
addSetMethods(clazz);
//处理没有get/set的方法字段
addFields(clazz);
//初始化可读写的名称集合
readablePropertyNames = getMethods.keySet().toArray(new String[getMethods.keySet().size()]);
writablePropertyNames = setMethods.keySet().toArray(new String[setMethods.keySet().size()]);
//初始化caseInsensitivePropertyMap ,记录了所有大写格式的属性名称
for (String propName : readablePropertyNames) {
caseInsensitivePropertyMap.put(propName.toUpperCase(Locale.ENGLISH), propName);
}
for (String propName : writablePropertyNames) {
caseInsensitivePropertyMap.put(propName.toUpperCase(Locale.ENGLISH), propName);
}
}
/**
* 将clazz的无参构造方法设置给defaultConstructor
*/
private void addDefaultConstructor(Class> clazz) {
Constructor>[] consts = clazz.getDeclaredConstructors();
for (Constructor> constructor : consts) {
if (constructor.getParameterTypes().length == 0) {
this.defaultConstructor = constructor;
}
}
}
/**
* 将clazz的get方法添加给defaultConstructor
*/
private void addGetMethods(Class> cls) {
Map> conflictingGetters = new HashMap<>();
Method[] methods = getClassMethods(cls);
for (Method method : methods) {
if (method.getParameterTypes().length > 0) {
continue;
}
String name = method.getName();
if ((name.startsWith("get") && name.length() > 3)
|| (name.startsWith("is") && name.length() > 2)) {//这里只会将getter和iser方法填进去,而get,is不会添加进去
name = PropertyNamer.methodToProperty(name);
addMethodConflict(conflictingGetters, name, method);//添加将name和method作为key/value添加到conflictingGetters上
}
}
resolveGetterConflicts(conflictingGetters);//到了这里,conflictingGetters只会存在getter和iser方法
}
/**
*
* 解决Getter冲突
* 根据JavaBeans的规范,检验POJO是否按照规范,且取出最优的getter/setter方法,没有找到的话,会抛出异常。
*/
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)) {//当返回值不为boolean的iser方法又有getter时,会被抛出异常
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")) {//属于is...
winner = candidate;
}
} else if (candidateType.isAssignableFrom(winnerType)) {//属于继承关系
// OK getter type is descendant
} else if (winnerType.isAssignableFrom(candidateType)) {//属于继承关系
winner = candidate;
} else {//当发现属性存在一个getter和一个iser的时候,两个方法返回值类型不一样,也没有继承关系,就会抛出异常
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);
}
}
private void addGetMethod(String name, Method method) {
if (isValidPropertyName(name)) {
getMethods.put(name, new MethodInvoker(method));
Type returnType = TypeParameterResolver.resolveReturnType(method, type);
getTypes.put(name, typeToClass(returnType));
}
}
private void addSetMethods(Class> cls) {
Map> conflictingSetters = new HashMap<>();
Method[] methods = getClassMethods(cls);
for (Method method : methods) {
String name = method.getName();
if (name.startsWith("set") && name.length() > 3) {//这里只会将set..方法填进去,而get,is不会添加进去
if (method.getParameterTypes().length == 1) {//只获取只有一个参数的方法
name = PropertyNamer.methodToProperty(name);
addMethodConflict(conflictingSetters, name, method);//添加将name和method作为key/value添加到conflictingSetters上
}
}
}
resolveSetterConflicts(conflictingSetters);
}
/**
* 添加方法method进conflictingMethods上。
* @param conflictingMethods
* @param name
* @param method
*/
private void addMethodConflict(Map> conflictingMethods, String name, Method method) {
List list = conflictingMethods.computeIfAbsent(name, k -> new ArrayList<>());
list.add(method);
}
private void resolveSetterConflicts(Map> conflictingSetters) {
for (String propName : conflictingSetters.keySet()) {
List setters = conflictingSetters.get(propName);
Class> getterType = getTypes.get(propName);
Method match = null;
ReflectionException exception = null;
for (Method setter : setters) {
Class> paramType = setter.getParameterTypes()[0];
if (paramType.equals(getterType)) {
// should be the best match
match = setter;
break;
}
if (exception == null) {
try {
match = pickBetterSetter(match, setter, propName);//传进来的match,setter是属于重载关系
} catch (ReflectionException e) {
// there could still be the 'best match'
match = null;
exception = e;
}
}
}
if (match == null) {
throw exception;
} else {
addSetMethod(propName, match);
}
}
}
/**
* 如果setter1和setter2的唯一参数是否存在继承关系,如果存在,取父类的setter方法。
*/
private Method pickBetterSetter(Method setter1, Method setter2, String property) {
if (setter1 == null) {
return setter2;
}
Class> paramType1 = setter1.getParameterTypes()[0];
Class> paramType2 = setter2.getParameterTypes()[0];
if (paramType1.isAssignableFrom(paramType2)) {
return setter2;
} else if (paramType2.isAssignableFrom(paramType1)) {
return setter1;
}
throw new ReflectionException("Ambiguous setters defined for property '" + property + "' in class '"
+ setter2.getDeclaringClass() + "' with types '" + paramType1.getName() + "' and '"
+ paramType2.getName() + "'.");
}
/**
* 判断属性name是否有效 {@link Reflector#isValidPropertyName(String)},
* 有则,构造一个method的 {@link MethodInvoker} 对象,放进setMethods对象中。
* 然后,获取method的第一个参数类型,放进setType中。
*/
private void addSetMethod(String name, Method method) {
if (isValidPropertyName(name)) {
setMethods.put(name, new MethodInvoker(method));
Type[] paramTypes = TypeParameterResolver.resolveParamTypes(method, type);
setTypes.put(name, typeToClass(paramTypes[0]));
}
}
/**
* 类型转换成类,没有找到,默认返回Object
*/
private Class> typeToClass(Type src) {
Class> result = null;
if (src instanceof Class) {//普通Java类
result = (Class>) src;
} else if (src instanceof ParameterizedType) {//普通泛型类
result = (Class>) ((ParameterizedType) src).getRawType();
} else if (src instanceof GenericArrayType) {//泛型数组
Type componentType = ((GenericArrayType) src).getGenericComponentType();
if (componentType instanceof Class) {//普通Java类数组
result = Array.newInstance((Class>) componentType, 0).getClass();
} else {//泛型数组
Class> componentClass = typeToClass(componentType);
result = Array.newInstance(componentClass, 0).getClass();
}
}
if (result == null) {//
result = Object.class;
}
return result;
}
/**
* 添加存在与类中,却没有getter方法或者没有setter方法的属性。包含父类的属性(递归)
* @param clazz
*/
private void addFields(Class> clazz) {
Field[] fields = clazz.getDeclaredFields();
for (Field field : fields) {
if (!setMethods.containsKey(field.getName())) {
// issue #379 - removed the check for final because JDK 1.5 allows
// modification of final fields through reflection (JSR-133). (JGB)
// pr #16 - final static can only be set by the classloader
int modifiers = field.getModifiers();
if (!(Modifier.isFinal(modifiers) && Modifier.isStatic(modifiers))) {//方法不是被final修饰,且不被static修饰时,返回true
addSetField(field);
}
}
if (!getMethods.containsKey(field.getName())) {
addGetField(field);
}
}
if (clazz.getSuperclass() != null) {
addFields(clazz.getSuperclass());
}
}
/**
* 判断属性field是否有效 {@link Reflector#isValidPropertyName(String)},
* 有则,构造一个field的 {@link SetFieldInvoker} 对象,放进setMethods对象中。
* 然后,获取field的在type中的属性类型,饭局setType中。
*/
private void addSetField(Field field) {
if (isValidPropertyName(field.getName())) {
setMethods.put(field.getName(), new SetFieldInvoker(field));
Type fieldType = TypeParameterResolver.resolveFieldType(field, type);
setTypes.put(field.getName(), typeToClass(fieldType));
}
}
/**
* 判断属性field是否有效 {@link Reflector#isValidPropertyName(String)},
* 有则,构造一个field的 {@link GetFieldInvoker} 对象,放进getMethods对象中。
* 然后,获取field的在type中的属性类型,饭局getTypes中。
*/
private void addGetField(Field field) {
if (isValidPropertyName(field.getName())) {
getMethods.put(field.getName(), new GetFieldInvoker(field));
Type fieldType = TypeParameterResolver.resolveFieldType(field, type);
getTypes.put(field.getName(), typeToClass(fieldType));
}
}
/**
* 只要name不是以'$'开头,或者name!='serialVersionUID',或者name!='class'就会返回true
* @param name
* @return
*/
private boolean isValidPropertyName(String name) {
return !(name.startsWith("$") || "serialVersionUID".equals(name) || "class".equals(name));
}
/**
* This method returns an array containing all methods
* declared in this class and any superclass.
* We use this method, instead of the simpler Class.getMethods()
,
* because we want to look for private methods as well.
* 获取当前类以及父类中定义的所有方法的唯一签名以及相应的Method对象
* @param cls The class
* @return An array containing all methods in this class
*/
private Method[] getClassMethods(Class> cls) {
Map uniqueMethods = new HashMap<>();
Class> currentClass = cls;
while (currentClass != null && currentClass != Object.class) {
//为每个方法生成唯一签名,并记录到uniqueMethods集合中
addUniqueMethods(uniqueMethods, currentClass.getDeclaredMethods());
// we also need to look for interface methods -
// because the class may be abstract
Class>[] interfaces = currentClass.getInterfaces();
for (Class> anInterface : interfaces) {
addUniqueMethods(uniqueMethods, anInterface.getMethods());
}
currentClass = currentClass.getSuperclass();
}
Collection methods = uniqueMethods.values();
return methods.toArray(new Method[methods.size()]);
}
/**
* 返回的方法可能存在,两个相同的方法名称,因为当子类实现父类方法时且参数不同,
* 此时生成的签名是不同的生成签名的规则是 方法返回值#方法名#参数名,那么就会返回两个相同的方法名
*/
private void addUniqueMethods(Map uniqueMethods, Method[] methods) {
for (Method currentMethod : methods) {
//判断是不是桥接方法, 桥接方法是 JDK 1.5 引入泛型后,为了使Java的泛型方法生成的字节码和 1.5 版本前的字节码相兼容,由编译器自动生成的方法
if (!currentMethod.isBridge()) {
//获取签名
// 签名格式为:方法返回参数#方法名:参数名 ps:多个参数用,分割 签名样例:String#getName:User
String signature = getSignature(currentMethod);
// check to see if the method is already known
// if it is known, then an extended class must have
// overridden a method
//如果签名存在,则不做处理,表示子类已经覆盖了该方法。
//如果签名不存在,则将签名作为Key,Method作为value 添加到uniqueMethods中
if (!uniqueMethods.containsKey(signature)) {
uniqueMethods.put(signature, currentMethod);
}
}
}
}
/**
* 返回参数#方法名:参数名 ps:多个参数用,分割 签名样例:java.lang.String#getName:java.lang.String
*/
private String getSignature(Method method) {
StringBuilder sb = new StringBuilder();
Class> returnType = method.getReturnType();
if (returnType != null) {
sb.append(returnType.getName()).append('#');
}
sb.append(method.getName());
Class>[] parameters = method.getParameterTypes();
for (int i = 0; i < parameters.length; i++) {
if (i == 0) {
sb.append(':');
} else {
sb.append(',');
}
sb.append(parameters[i].getName());
}
return sb.toString();
}
/**
* Checks whether can control member accessible.
* 从java安全管理器中获取suppressAccessChecks反射权限是否存在,存在返回true,否则false
* @return If can control member accessible, it return {@literal true}
* @since 3.5.0
*/
public static boolean canControlMemberAccessible() {
try {
SecurityManager securityManager = System.getSecurityManager();
if (null != securityManager) {
securityManager.checkPermission(new ReflectPermission("suppressAccessChecks"));
}
} catch (SecurityException e) {
return false;
}
return true;
}
/**
* Gets the name of the class the instance provides information for.
*
* @return The class name
*/
public Class> getType() {
return type;
}
public Constructor> getDefaultConstructor() {
if (defaultConstructor != null) {
return defaultConstructor;
} else {
throw new ReflectionException("There is no default constructor for " + type);
}
}
/**
* 是否存在无参构造方法
* @return
*/
public boolean hasDefaultConstructor() {
return defaultConstructor != null;
}
/**
* 从setMethods计划中获取对应propertyName的setter方法的执行器,没有找到会抛出ReflectionException
*/
public Invoker getSetInvoker(String propertyName) {
Invoker method = setMethods.get(propertyName);
if (method == null) {
throw new ReflectionException("There is no setter for property named '" + propertyName + "' in '" + type + "'");
}
return method;
}
/**
* 从getMethods计划中获取对应propertyName的getter方法的执行器,没有找到会抛出ReflectionException
*/
public Invoker getGetInvoker(String propertyName) {
Invoker method = getMethods.get(propertyName);
if (method == null) {
throw new ReflectionException("There is no getter for property named '" + propertyName + "' in '" + type + "'");
}
return method;
}
/**
* Gets the type for a property setter.
* 返回参数propertyName对应的setter方法的参数类型
* @param propertyName - the name of the property
* @return The Class of the property setter
*/
public Class> getSetterType(String propertyName) {
Class> clazz = setTypes.get(propertyName);
if (clazz == null) {
throw new ReflectionException("There is no setter for property named '" + propertyName + "' in '" + type + "'");
}
return clazz;
}
/**
* Gets the type for a property getter.
* 获取类中属性的getter方法的返回类型
* @param propertyName - the name of the property
* @return The Class of the property getter
*/
public Class> getGetterType(String propertyName) {
Class> clazz = getTypes.get(propertyName);
if (clazz == null) {
throw new ReflectionException("There is no getter for property named '" + propertyName + "' in '" + type + "'");
}
return clazz;
}
/**
* Gets an array of the readable properties for an object.
* 存在相应getter 方法的所有属性
* @return The array
*/
public String[] getGetablePropertyNames() {
return readablePropertyNames;
}
/**
* Gets an array of the writable properties for an object.
* 存在相应setter 方法的所有属性
* @return The array
*/
public String[] getSetablePropertyNames() {
return writablePropertyNames;
}
/**
* Check to see if a class has a writable property by name.
* 从getMethods中获取对应(参数propertyName)的setter方法
* @param propertyName - the name of the property to check
* @return True if the object has a writable property by the name
*/
public boolean hasSetter(String propertyName) {
return setMethods.keySet().contains(propertyName);
}
/**
* Check to see if a class has a readable property by name.
* 从getMethods中获取对应(参数propertyName)的getter方法
* @param propertyName - the name of the property to check
* @return True if the object has a readable property by the name
*/
public boolean hasGetter(String propertyName) {
return getMethods.keySet().contains(propertyName);
}
/**
* 将name改成全大小,然后从 不区分属性名称Map caseInsensitivePropertyMap 拿到类的真实属性名称
*/
public String findPropertyName(String name) {
return caseInsensitivePropertyMap.get(name.toUpperCase(Locale.ENGLISH));
}
}