基于Mybatis-3.5.0版本java
org.apache.ibatis.reflection.Reflector
反射器,每一个Reflector对应一个类,会缓存反射操做须要的类的元数据,例如:构造方法、属性名、get/set方法等等。代码以下:apache
/** * This class represents a cached set of class definition information that * allows for easy mapping between property names and getter/setter methods. * * 反射器,每一个 Reflector对应一个类, 会缓存类的元信息, * 此类表示一组缓存的类的元数据,容许在属性名和getter/setter方法之间轻松映射。 * @author Clinton Begin */
public class Reflector {
// 对应类的Class对象
private final Class<?> type;
// 可读属性数组
private final String[] readablePropertyNames;
// 可写属性数组
private final String[] writeablePropertyNames;
// key是属性名称,value是Invoker对象
/** * Invoker接口:适配器模式用于消除java bean的 * getter方法、setter方法、Filed属性的set/get的操做差别 */
private final Map<String, Invoker> setMethods = new HashMap<>();
// key是属性名称,value是Invoker对象
private final Map<String, Invoker> getMethods = new HashMap<>();
// key是属性名称,value是setter方法的参数值类型
private final Map<String, Class<?>> setTypes = new HashMap<>();
// key是属性名称,value是getter方法的返回值类型
private final Map<String, Class<?>> getTypes = new HashMap<>();
// 默认无参构造器
private Constructor<?> defaultConstructor;
// 不区分大小写的属性集合 key:toUpperCase的属性名称 value:原属性名称
private Map<String, String> caseInsensitivePropertyMap = new HashMap<>();
public Reflector(Class<?> clazz) {
type = clazz;
addDefaultConstructor(clazz);
addGetMethods(clazz);
addSetMethods(clazz);
addFields(clazz);
readablePropertyNames = getMethods.keySet().toArray(new String[getMethods.keySet().size()]);
writeablePropertyNames = setMethods.keySet().toArray(new String[setMethods.keySet().size()]);
for (String propName : readablePropertyNames) {
caseInsensitivePropertyMap.put(propName.toUpperCase(Locale.ENGLISH), propName);
}
for (String propName : writeablePropertyNames) {
caseInsensitivePropertyMap.put(propName.toUpperCase(Locale.ENGLISH), propName);
}
}
/** * 初始化defaultConstructor * @param clazz */
private void addDefaultConstructor(Class<?> clazz) {
// 获取全部声明的构造方法
Constructor<?>[] consts = clazz.getDeclaredConstructors();
for (Constructor<?> constructor : consts) {
// 参数数量为0,即没有参数的构造方法为 默认构造方法
if (constructor.getParameterTypes().length == 0) {
this.defaultConstructor = constructor;
}
}
}
/** * 初始化getMethods和getTypes * @param cls */
private void addGetMethods(Class<?> cls) {
// key:属性名称,value:getter方法集合
/** * 由于在java的继承关系中,会存在子类重写父类的方法,可是放大了返回值类型 全部会存在conflicting冲突的方法 * 例: * super: List<String> getIds(); * sub: ArrayList<String> getIds(); */
Map<String, List<Method>> conflictingGetters = new HashMap<>();
// 获取全部方法
Method[] methods = getClassMethods(cls);
/** * 循环添加规范的getter方法 * java bean getter规范: * 1.没有参数 * 2.若以get开头,方法长度大于3 * 3.若以is开头,方法长度大于2 */
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)) {
name = PropertyNamer.methodToProperty(name);
addMethodConflict(conflictingGetters, name, method);
}
}
// 解决冲突的方法,将最合适的方法添加到getMethods和getTypes
resolveGetterConflicts(conflictingGetters);
}
/** * 解决getter方法冲突,寻找最规范和最合理的getter方法 * 冲突缘由:由于在java的继承关系中,会存在子类重写父类的方法,可是放大了返回值类型 全部会存在conflicting冲突的方法 * 例: * super: List<String> getIds(); * sub: ArrayList<String> getIds(); * * @param conflictingGetters */
private void resolveGetterConflicts(Map<String, List<Method>> conflictingGetters) {
for (Entry<String, List<Method>> entry : conflictingGetters.entrySet()) {
Method winner = null;//胜利者 即最规范最合理的getter方法
String propName = entry.getKey();
for (Method candidate : entry.getValue()) {
if (winner == null) {
winner = candidate;
continue;
}
/** * 若是返回类型相同,不是boolean类型报异常,以is开头的方法为主 * 主要解决Boolean类型属性,命名不规范 例: getFlag() 与 isFlag() */
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;
}
/** * isAssignableFrom()方法是从类继承的角度去判断,判断是否为某个类的父类 * instanceof()方法是从实例继承的角度去判断,是判断是否某个类的子类。 * 以子类返回类型为主:针对一些重写的场景,子类放大了返回值 * 例如: 父类的一个方法的返回值为 List ,子类对该方法的返回值能够覆写为 ArrayList */
} 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);
}
}
/** * 缓存Getter方法和Getter方法的返回值类型 * @param name * @param method */
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));
}
}
/** * 初始化 setMethods和setTypes属性 * 整个流程和初始化Getter方法相似 * @param cls */
private void addSetMethods(Class<?> cls) {
Map<String, List<Method>> conflictingSetters = new HashMap<>();
Method[] methods = getClassMethods(cls);
for (Method method : methods) {
String name = method.getName();
if (name.startsWith("set") && name.length() > 3) {
if (method.getParameterTypes().length == 1) {
name = PropertyNamer.methodToProperty(name);
addMethodConflict(conflictingSetters, name, method);
}
}
}
resolveSetterConflicts(conflictingSetters);
}
/** * java8 Map default computeIfAbsent方法 * put key,存在则返回value,不存在建立value并put(key,vlue) 返回value * @param conflictingMethods * @param name * @param method */
private void addMethodConflict(Map<String, List<Method>> conflictingMethods, String name, Method method) {
List<Method> list = conflictingMethods.computeIfAbsent(name, k -> new ArrayList<>());
list.add(method);
}
/** * 解决Setter方法冲突,保证最规范在最合理的Setter方法 * @param conflictingSetters */
private void resolveSetterConflicts(Map<String, List<Method>> conflictingSetters) {
for (String propName : conflictingSetters.keySet()) {
List<Method> setters = conflictingSetters.get(propName);
Class<?> getterType = getTypes.get(propName);
Method match = null;
ReflectionException exception = null;
for (Method setter : setters) {
Class<?> paramType = setter.getParameterTypes()[0];
//setter对应的参数类型与该属性对应的getter的响应值类型一致则是合理的setter方法
if (paramType.equals(getterType)) {
// should be the best match
match = setter;
break;
}
if (exception == null) {
try {
match = pickBetterSetter(match, setter, propName);
} catch (ReflectionException e) {
// there could still be the 'best match'
match = null;
exception = e;
}
}
}
if (match == null) {
throw exception;
} else {
addSetMethod(propName, match);
}
}
}
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() + "'.");
}
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]));
}
}
private Class<?> typeToClass(Type src) {
Class<?> result = null;
if (src instanceof Class) {
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) {
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;
}
/** * 初始化setMethods和setTypes属性和getMethods和getTypes属性 * 主要处理一些属性没有对应的getter和setter方法的状况 * @param clazz */
private void addFields(Class<?> clazz) {
// 获取声明的属性对象
Field[] fields = clazz.getDeclaredFields();
for (Field field : fields) {
// setter缓存里面不存在的就处理
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
// 过滤掉final和static修饰的字段
int modifiers = field.getModifiers();
if (!(Modifier.isFinal(modifiers) && Modifier.isStatic(modifiers))) {
addSetField(field);
}
}
// getter缓存里面不存在的就处理
if (!getMethods.containsKey(field.getName())) {
addGetField(field);
}
}
// 若是有父类则递归处理
if (clazz.getSuperclass() != null) {
addFields(clazz.getSuperclass());
}
}
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));
}
}
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));
}
}
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. * * @param cls The class * @return An array containing all methods in this class */
private Method[] getClassMethods(Class<?> cls) {
// key:方法签名,value:Method方法
Map<String, Method> uniqueMethods = new HashMap<>();
Class<?> currentClass = cls;
// 循环类,类的父类,类的父类的父类,直到父类为 Object
while (currentClass != null && currentClass != Object.class) {
// 记录当前类定义的方法
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<Method> methods = uniqueMethods.values();
return methods.toArray(new Method[methods.size()]);
}
/** * 添加方法签名惟一的方法 * @param uniqueMethods * @param methods */
private void addUniqueMethods(Map<String, Method> uniqueMethods, Method[] methods) {
for (Method currentMethod : methods) {
if (!currentMethod.isBridge()) {// bridge方法不处理
// 获取方法签名
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
if (!uniqueMethods.containsKey(signature)) {
uniqueMethods.put(signature, currentMethod);
}
}
}
}
/** * 获取方法签名 * 格式:响应值类型名称方法名称:方法参数类型名称 * 例: * void#setId:java.lang.Long * @param method * @return */
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. * 检查是否能够控制成员的访问性 * @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);
}
}
public boolean hasDefaultConstructor() {
return defaultConstructor != null;
}
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;
}
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 * * @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 * * @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 * * @return The array */
public String[] getGetablePropertyNames() {
return readablePropertyNames;
}
/** * Gets an array of the writable properties for an object * * @return The array */
public String[] getSetablePropertyNames() {
return writeablePropertyNames;
}
/** * Check to see if a class has a writable property by name * * @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 * * @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);
}
public String findPropertyName(String name) {
return caseInsensitivePropertyMap.get(name.toUpperCase(Locale.ENGLISH));
}
}
复制代码
org.apache.ibatis.reflection.ReflectorFactory
Reflector工厂接口用于直接根据Class对象建立Reflector对象,并提供了缓存功能。代码以下:数组
public interface ReflectorFactory {
boolean isClassCacheEnabled();
void setClassCacheEnabled(boolean classCacheEnabled);
Reflector findForClass(Class<?> type);
}
复制代码
org.apache.ibatis.reflection.DefaultReflectorFactory
默认Reflector工厂接口实现类,代码以下:缓存
public class DefaultReflectorFactory implements ReflectorFactory {
// 是否开启缓存
private boolean classCacheEnabled = true;
/** * ConcurrentMap 缓存Reflector信息 key:Class value:Class对应的Reflector */
private final ConcurrentMap<Class<?>, Reflector> reflectorMap = new ConcurrentHashMap<>();
public DefaultReflectorFactory() {
}
@Override
public boolean isClassCacheEnabled() {
return classCacheEnabled;
}
@Override
public void setClassCacheEnabled(boolean classCacheEnabled) {
this.classCacheEnabled = classCacheEnabled;
}
/** * 开启缓存:则直接从reflectorMap获取,未获取到则建立Reflector对象放入map并返回 * 未开启缓存:每次都建立新的Reflector对象 */
@Override
public Reflector findForClass(Class<?> type) {
if (classCacheEnabled) {
// synchronized (type) removed see issue #461
return reflectorMap.computeIfAbsent(type, Reflector::new);
} else {
return new Reflector(type);
}
}
}
复制代码
java8 新特性:default方法
默认方法使得开发者能够在不破坏二进制兼容性的前提下,往现存接口中添加新的方法,即不强制那些实现了该接口的类也同时实现这个新加的方法。app
computeIfAbsent
方法为Map类下面的默认方法,代码以下:ide
//put key,存在则返回value,不存在建立value并put(key,vlue) 返回value
default V computeIfAbsent(K key, Function<? super K, ? extends V> mappingFunction) {
Objects.requireNonNull(mappingFunction);
V v;
if ((v = get(key)) == null) {
V newValue;
if ((newValue = mappingFunction.apply(key)) != null) {
put(key, newValue);
return newValue;
}
}
return v;
}
复制代码
特别适用于一些value为集合类型的数据,能够看下Mybatis3.4.6版本和3.5.0版本的代码差别:学习
//3.5.0
private void addMethodConflict(Map<String, List<Method>> conflictingMethods, String name, Method method) {
List<Method> list = conflictingMethods.computeIfAbsent(name, k -> new ArrayList<>());
list.add(method);
}
//3.4.6
private void addMethodConflict(Map<String, List<Method>> conflictingMethods, String name, Method method) {
List<Method> list = conflictingMethods.get(name);
if (list == null) {
list = new ArrayList<Method>();
conflictingMethods.put(name, list);
}
list.add(method);
}
复制代码
关于Method isBridge()方法,主要针对一些泛型方法,由于泛型擦除的缘由,致使重载的方法失去意义,因此会在对应的类里面注入一个bridge方法,见下例: Java反射中method.isBridge()由来,含义和使用场景ui
interface A<T> {
void func(T t);
}
class B implements A<String> {
@Override
public void func(String t) {
System.out.println(t);
}
}
public static void main(String[] args) throws Exception {
B obj = new B();
Method func = B.class.getMethod("func", String.class);
func.invoke(obj, "AAA");
System.out.println(func.isBridge());
func = B.class.getMethod("func", Object.class);
func.invoke(obj, "BBB");
System.out.println(func.isBridge());
}
console:
AAA
false
BBB
true
复制代码
isAssignableFrom 与 instanceof的差别:this
例:spa
List<String> list = new ArrayList<>();
ArrayList.class.isAssignableFrom(List.class)// false
list instanceof List // true
复制代码
看完Reflector的代码,小菜阿甘有3个方面的感悟:
失控的阿甘,乐于分享,记录点滴