Mybatis框架基础支持层——反射工具箱之Reflector&ReflectorFactory(3)

说明:Reflector是Mybatis反射工具的基础,每个Reflector对应一个类,在Reflector中封装有该类的元信息,

以及基于类信息的一系列反射应用封装API

public class Reflector {

    private static final String[] EMPTY_STRING_ARRAY = new String[0];

    /**
     * 对应的类Class对象
     */
    private Class<?> type;
    /**
     * 类中可读属性的集合,就是存在相应的getter方法的属性
     */
    private String[] readablePropertyNames = EMPTY_STRING_ARRAY;
    /**
     * 类中可写属性的集合,就是存在相应的setter方法的属性
     */
    private String[] writeablePropertyNames = EMPTY_STRING_ARRAY;
    /**
     * 记录了属性相应的setter方法,key是属性名称,value是invoker对象,
     * invoker是对setter方法对应Method对象的封装
     */
    private Map<String, Invoker> setMethods = new HashMap<String, Invoker>();
    /**
     * 记录了属性相应的getter方法,key是属性名称,value是invoker对象,
     * invoker是对getter方法对应Method对象的封装
     */
    private Map<String, Invoker> getMethods = new HashMap<String, Invoker>();
    /**
     * 记录了属性相应的setter方法的参数值类型,key是属性名称,value是setter方法的参数值类型
     */
    private Map<String, Class<?>> setTypes = new HashMap<String, Class<?>>();
    /**
     * 记录了属性相应的getter方法的返回值类型,key是属性名称,value是getter方法的返回值类型
     */
    private Map<String, Class<?>> getTypes = new HashMap<String, Class<?>>();
    /**
     * 记录了默认构造方法
     */
    private Constructor<?> defaultConstructor;
    /**
     * 记录了所有属性名称的集合
     */
    private Map<String, String> caseInsensitivePropertyMap = new HashMap<String, String>();

    /**
     * 在Reflector构造方法中会指定某个类的Class对象,并填充上述集合
     */
    public Reflector(Class<?> clazz) {
        type = clazz;
        /**
         * 查找clazz的默认构造方法(无参构造)
         */
        addDefaultConstructor(clazz);
        /**
         * 处理clazz中的getter方法,填充getMethods集合和getTypes集合
         */
        addGetMethods(clazz);
        /**
         * 处理clazz中的setter方法,填充setMethods集合和setTypes集合
         */
        addSetMethods(clazz);
        /**
         * 处理没有getter/setter方法的字段
         */
        addFields(clazz);
        /**
         * 根据getMethods、setMethods集合,初始化可读/写属性名称的集合
         */
        readablePropertyNames = getMethods.keySet().toArray(new String[getMethods.keySet().size()]);
        writeablePropertyNames = setMethods.keySet().toArray(new String[setMethods.keySet().size()]);

        /**
         * 初始化caseInsensitivePropertyMap,其中记录了所有大写格式的属性名称
         */
        for (String propName : readablePropertyNames) {
            caseInsensitivePropertyMap.put(propName.toUpperCase(Locale.ENGLISH), propName);
        }
        for (String propName : writeablePropertyNames) {
            caseInsensitivePropertyMap.put(propName.toUpperCase(Locale.ENGLISH), propName);
        }
    }

    private void addDefaultConstructor(Class<?> clazz) {
        /**
         * 返回类中声明的所有构造函数Constructor,包括public、protected、default、private声明
         * 如果Class对象是一个接口、抽象类、数组类或void,则返回length=0的Constructor数组
         */
        Constructor<?>[] consts = clazz.getDeclaredConstructors();
        for (Constructor<?> constructor : consts) {
            if (constructor.getParameterTypes().length == 0) {
                if (canAccessPrivateMethods()) {
                    try {
                        constructor.setAccessible(true);
                    } catch (Exception e) {
                        // Ignored. This is only a final precaution, nothing we can do.
                    }
                }
                if (constructor.isAccessible()) {
                    this.defaultConstructor = constructor;
                }
            }
        }
    }

    private void addGetMethods(Class<?> cls) {
        Map<String, List<Method>> conflictingGetters = new HashMap<String, List<Method>>();
        /**
         * 获取当前类中所有的方法,包括自己、父类、父类的父类...,接口等
         */
        Method[] methods = getClassMethods(cls);
        for (Method method : methods) {
            String name = method.getName();
            if (name.startsWith("get") && name.length() > 3) {
                if (method.getParameterTypes().length == 0) {
                    /**
                     * PropertyNamer:
                     * setter、getter方法名=>属性名称转换,和属性getter、setter方法判断
                     */
                    name = PropertyNamer.methodToProperty(name);
                    addMethodConflict(conflictingGetters, name, method);
                }
            } else if (name.startsWith("is") && name.length() > 2) {
                if (method.getParameterTypes().length == 0) {
                    name = PropertyNamer.methodToProperty(name);
                    addMethodConflict(conflictingGetters, name, method);
                }
            }
        }
        //填充getMethods和getTypes集合
        resolveGetterConflicts(conflictingGetters);
    }

    private void resolveGetterConflicts(Map<String, List<Method>> conflictingGetters) {
        for (String propName : conflictingGetters.keySet()) {
            List<Method> getters = conflictingGetters.get(propName);
            Iterator<Method> iterator = getters.iterator();
            Method firstMethod = iterator.next();
            if (getters.size() == 1) {
                addGetMethod(propName, firstMethod);
            } else {
                Method getter = firstMethod;
                Class<?> getterType = firstMethod.getReturnType();
                while (iterator.hasNext()) {
                    Method method = iterator.next();
                    Class<?> methodType = method.getReturnType();
                    if (methodType.equals(getterType)) {
                        throw new ReflectionException("Illegal overloaded getter method with ambiguous type for property "
                                + propName + " in class " + firstMethod.getDeclaringClass()
                                + ".  This breaks the JavaBeans " + "specification and can cause unpredictable results.");
                    } else if (methodType.isAssignableFrom(getterType)) {
                        // OK getter type is descendant
                    } else if (getterType.isAssignableFrom(methodType)) {
                        getter = method;
                        getterType = methodType;
                    } else {
                        throw new ReflectionException("Illegal overloaded getter method with ambiguous type for property "
                                + propName + " in class " + firstMethod.getDeclaringClass()
                                + ".  This breaks the JavaBeans " + "specification and can cause unpredictable results.");
                    }
                }
                addGetMethod(propName, getter);
            }
        }
    }

    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<String, List<Method>> conflictingSetters = new HashMap<String, List<Method>>();
        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);
    }

    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);
    }

    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];
                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((Class<?>) componentClass, 0).getClass();
            }
        }
        if (result == null) {
            result = Object.class;
        }
        return result;
    }

    private void addFields(Class<?> clazz) {
        Field[] fields = clazz.getDeclaredFields();
        for (Field field : fields) {
            if (canAccessPrivateMethods()) {
                try {
                    field.setAccessible(true);
                } catch (Exception e) {
                    // Ignored. This is only a final precaution, nothing we can do.
                }
            }
            if (field.isAccessible()) {
                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))) {
                        addSetField(field);
                    }
                }
                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<String, Method>();
        Class<?> currentClass = cls;
        while (currentClass != null) {
            /**
             * currentClass.getDeclaredMethods()返回当前类或接口中所有被声明的方法,包括
             * public、protected、default、private,但是排除集成的方法
             *
             * 此方法是将当前类中非桥接(下文有介绍)方法填入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());
            }
            /**
             * Returns the {@code Class} representing the superclass of the entity
             * (class, interface, primitive type or void) represented by this
             * {@code Class}.  If this {@code Class} represents either the
             * {@code Object} class, an interface, a primitive type, or void, then
             * null is returned.  If this object represents an array class then the
             * {@code Class} object representing the {@code Object} class is
             * returned
             */
            currentClass = currentClass.getSuperclass();
        }

        Collection<Method> methods = uniqueMethods.values();

        return methods.toArray(new Method[methods.size()]);
    }

    private void addUniqueMethods(Map<String, Method> uniqueMethods, Method[] methods) {
        for (Method currentMethod : methods) {
            /**
             * 桥接方法是 JDK 1.5 引入泛型后,为了使Java的泛型方法生成的字节码和 1.5 版本前的字节码相兼容,
             * 由编译器自动生成的方法。我们可以通过Method.isBridge()方法来判断一个方法是否是桥接方法。
             */
            if (!currentMethod.isBridge()) {
                //获取当前方法的签名
                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)) {
                    if (canAccessPrivateMethods()) {
                        try {
                            currentMethod.setAccessible(true);
                        } catch (Exception e) {
                            // Ignored. This is only a final precaution, nothing we can do.
                        }
                    }

                    uniqueMethods.put(signature, currentMethod);
                }
            }
        }
    }
    /**
     * 获取一个方法的签名,根据方法的返回值、方法、方法参数构建一个签名
     */
    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();
    }

    private static boolean canAccessPrivateMethods() {
        try {
            //java安全管理器具体细节,可看博客中另一篇介绍
            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 propery 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 propery 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 writeable properties for an object
     *
     * @return The array
     */
    public String[] getSetablePropertyNames() {
        return writeablePropertyNames;
    }

    /*
     * Check to see if a class has a writeable property by name
     *
     * @param propertyName - the name of the property to check
     * @return True if the object has a writeable 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));
    }
}

ReflectorFactory接口主要实现了对Reflector对象的创建和缓存,Mybatis为该接口提供了仅有的一个实现类DefaultReflectorFactory:

public interface ReflectorFactory {

    /**
     * 检测ReflectorFactory对象是否启用缓存Reflector功能
     */
    boolean isClassCacheEnabled();

    /**
     * 设置ReflectorFactory对象是否启用缓存Reflector功能
     */
    void setClassCacheEnabled(boolean classCacheEnabled);

    /**
     * 创建指定Class对象对应的Reflector,如果缓存有,就从缓存取,否则新建一个
     */
    Reflector findForClass(Class<?> type);
}
public class DefaultReflectorFactory implements ReflectorFactory {
    /**
     * 默认启用缓存Reflector的功能
     */
    private boolean classCacheEnabled = true;
    /**
     * 缓存Reflector的数据结构,key[Class对象],value[Class对应的Reflector对象]
     */
    private final ConcurrentMap<Class<?>, Reflector> reflectorMap = new ConcurrentHashMap<Class<?>, Reflector>();

    public DefaultReflectorFactory() {
    }

    @Override
    public boolean isClassCacheEnabled() {
        return classCacheEnabled;
    }

    @Override
    public void setClassCacheEnabled(boolean classCacheEnabled) {
        this.classCacheEnabled = classCacheEnabled;
    }

    @Override
    public Reflector findForClass(Class<?> type) {
        if (classCacheEnabled) {
            // synchronized (type) removed see issue #461
            Reflector cached = reflectorMap.get(type);
            if (cached == null) {
                cached = new Reflector(type);
                reflectorMap.put(type, cached);
            }
            return cached;
        } else {
            return new Reflector(type);
        }
    }
}

原文地址:https://www.cnblogs.com/wly1-6/p/10284149.html

时间: 2024-09-29 00:56:48

Mybatis框架基础支持层——反射工具箱之Reflector&ReflectorFactory(3)的相关文章

Mybatis框架基础支持层——反射工具箱之MetaClass(7)

简介:MetaClass是Mybatis对类级别的元信息的封装和处理,通过与属性工具类的结合, 实现了对复杂表达式的解析,实现了获取指定描述信息的功能 public class MetaClass { private ReflectorFactory reflectorFactory; private Reflector reflector; /** * 构造函数私有 */ private MetaClass(Class<?> type, ReflectorFactory reflectorF

Mybatis框架基础支持层——解析器模块(2)

解析器模块,核心类XPathParser /** * 封装了用于xml解析的类XPath.Document和EntityResolver */ public class XPathParser { /** * 将xml文件读入内存,并构建一棵树, * 通过树结构对各个节点node进行操作 */ private Document document; /** * 是否开启xml文本格式验证 */ private boolean validation; /** * 用于加载本地DTD文件 * * 默认

MyBatis源码分析-基础支持层反射模块Reflector/ReflectorFactory

本文主要介绍MyBatis的反射模块是如何实现的. MyBatis 反射的核心类Reflector,下面我先说明它的构造函数和成员变量.具体方法下面详解. org.apache.ibatis.reflection.Reflector public class Reflector { private final Class<?> type; //对应的Class 类型 //可读属性的名称集合,可读属性就是存在相应getter 方法的属性,初始值为空数纽 private final String[

Mybatis框架--基础使用的一些坑

1 mybatis的底层实现 使用dom4j将配置文件读取出来,使用动态代理动态创建代理对象,中间的调用方法和过程是使用java的反射机制 2 数据库字段和属性名不一致的问题 1 在查询语句中使用别名 <select id="selectBlog2" parameterType="int" resultType="Blog">        select        `id`,        `title`,        `aut

框架基础(注解+反射)

创建布局注解类MyContentView.java,代码如下: @Retention(RetentionPolicy.RUNTIME) @Target({ElementType.TYPE}) public @interface MyContentView { int value(); } 创建控件注解类MyViewInject.java,代码如下: @Retention(RetentionPolicy.RUNTIME) @Target(ElementType.FIELD) public @int

Spring整合Mybatis框架-为业务层添加声明式事务控制 要么都成功要么都失败

其实上面一个例子,是看不出事务控制的,接下来,我们模拟一下真实的业务场景,一次添加一批用户,我们现在想要的结果是:要么都添加成功,要么都添加失败 只需要在上一个小demo的基础上进行稍微的改动就可以 UserServiceImpl.java   循环去调用添加用的方法 测试方法: 1 @Test 2 public void testAdd(){ 3 logger.debug("testAdd !==================="); 4 5 try { 6 Application

框架 day65 Mybatis入门(基础知识:框架原理,入门[curd],开发dao层,全局与映射配置)

Mybatis 基础知识(一) 第一天:基础知识(重点) mybatis介绍 mybatis框架原理(掌握) mybaits入门程序(掌握) 用户信息进行增.删.改.查 mybatis开发dao层方法:(掌握) 原始dao开发方法(dao接口和实现类需要程序员编写) mapper代理开发方法(程序员只需要编写接口) SqlMapConfig.xml(mybatis全局配置文件)(掌握) mybatis输入映射(掌握) mybatis输出映射(掌握) mybatis动态sql(掌握)   1   

SpringBoot2.0 基础案例(10):整合Mybatis框架,集成分页助手插件

一.Mybatis框架 1.mybatis简介 MyBatis 是一款优秀的持久层框架,它支持定制化 SQL.存储过程以及高级映射.MyBatis 避免了几乎所有的 JDBC 代码和手动设置参数以及获取结果集.MyBatis 可以使用简单的 XML 或注解来配置和映射原生类型.接口和 Java 的 POJO(Plain Old Java Objects,普通老式 Java 对象)为数据库中的记录. 2.mybatis特点 1)sql语句与代码分离,存放于xml配置文件中,方便管理 2)用逻辑标签

利用反射搭建项目的dao层,从此可以告别被人的dao层框架了(spring+反射)

作为一名刚入手的小白程序猿,不但"TA"不懂我们,就连自己都不懂自己,苦逼的程序猿,只能每天都是在给自己充电了.让"TA"和自己更了解.今天笔者又来吹吹水了,各位客官请买好零食咯,好了废话不多说了. 在以前做项目的时候,一般想到搭项目都是用别人的框架来做,但是别人的框架都是别人封装好的很多东西,对不太熟源码的码农来说就是苦逼呀,所以像笔者这种小白又不甘心,所以笔者就用反射来自己封装一个操作dao层的框架(不算一个框架,就是这么称呼吧),说起反射可能是很多像笔者这样的