2021-11-29 Spring源码中给某个bean的构造方

2021-11-29  本文已影响0人  归去来ming

排序的结果是:先按访问权限优先级,如果相同则参数多的排前面,权限不同,则public排最前面,private第二,protected第三;

abstract class AutowireUtils {

    /**
     * Sort the given constructors, preferring public constructors and "greedy" ones with
     * a maximum number of arguments. The result will contain public constructors first,
     * with decreasing number of arguments, then non-public constructors, again with
     * decreasing number of arguments.
     * @param constructors the constructor array to sort
     */
    public static void sortConstructors(Constructor<?>[] constructors) {
        Arrays.sort(constructors, new Comparator<Constructor<?>>() {
            @Override
            public int compare(Constructor<?> c1, Constructor<?> c2) {
                boolean p1 = Modifier.isPublic(c1.getModifiers());
                boolean p2 = Modifier.isPublic(c2.getModifiers());
                /**
                    返回-1,就是按从小到大,顺序排序;
                    返回1,就是按从大到小,逆序排序
                    而public的数值最小,排最前面
                    例如:
                    1 public Foo(Object o1, Object o2, Object o3)
                    2 public Foo(Object o1, Object o2)
                    3 public Foo(Object o1)
                    4 private Foo(String str, Object o1, Object o2, Object o3)
                    5 private Foo(String str, Object o1, Object o2)
                    6 private Foo(String str, Object o1)

                */
                if (p1 != p2) {
                    return (p1 ? -1 : 1);
                }
                int c1pl = c1.getParameterTypes().length;
                int c2pl = c2.getParameterTypes().length;
                // 返回1,参数多的就排前面,是逆序排序
                return (c1pl < c2pl ? 1 : (c1pl > c2pl ? -1 : 0));
            }
        });
    }

// 省略其它
}

访问权限修饰符Modifier

// java.lang.reflect.Modifier
    /**
     * The {@code int} value representing the {@code public}
     * modifier.
     */
    // 此处的1,十进制是1,二进制表示 0001
    public static final int PUBLIC           = 0x00000001;

    /**
     * The {@code int} value representing the {@code private}
     * modifier.
     */
    // 此处的2,十进制是2,二进制表示 0010
    public static final int PRIVATE          = 0x00000002;

    /**
     * The {@code int} value representing the {@code protected}
     * modifier.
     */
    // 此处的4,十进制是4,二进制表示 0100
    public static final int PROTECTED        = 0x00000004;
上一篇 下一篇

猜你喜欢

热点阅读