Java源码解析(5) —— Class(4)

Class最后一部分源码,这一部分大都是private方法、属性、类,都是Class本身各种方法的实现细节,涉及到了很多Class的实现原理,较为深奥,网上能找到的资料也比较少,目前只懂皮毛,仅供参考,所以,我这一部分说的可能是不正确的,需要抱着怀疑的态度看待!咳,就这样,闪人。

//缓存反射的数据信息
private volatile transient SoftReference<ReflectionData<T>> reflectionData;
//由JVM自动增加,表示虚拟机内,该类被重新定义的次数,JVM TI可以动态更新类定义
//关于类的动态定义这一点,可以参考:
//  http://blog.csdn.net/raintungli/article/details/51655608
private volatile transient int classRedefinedCount = 0;
    private ReflectionData<T> reflectionData() {
        //获取缓存中的反射数据,如果没启用缓存,或者没数据,则调用下面方法,新建反射缓存数据
    }
private ReflectionData<T> newReflectionData(SoftReference<ReflectionData<T>> oldReflectionData,
                                                int classRedefinedCount) {
       ......
    }
/**
 * 查看该类是否是泛型,虽然jdk上面说的是签名的handler(虽然我也不太明白这签名是什么),
 * 但是我查到,很多地方,包括Class源码上面判断泛型相关,都有类似这句代码:
 *  if (getGenericSignature() != null)
 * 详见:getGenericInterfaces()方法以及类似方法
 */
//
private native String getGenericSignature();
/**
 * 该类的类型仓库,其主要作用是操作及缓存该类的类型信息以及父类信息,比如其内就有泛型
 * 工厂对象,和父类对象类型信息及所实现的父类接口信息
 */
private transient ClassRepository genericInfo;

/**
 * GenericsFactory:泛型工厂,用来生产及操作各种类型对象(Java类型详见:)
 * http://blog.csdn.net/a327369238/article/details/52621043
 */
private GenericsFactory getFactory() {
        return CoreReflectionFactory.make(this, ClassScope.make(this));
    }
    private ClassRepository getGenericInfo() {
        if (genericInfo == null) {
            genericInfo = ClassRepository.make(getGenericSignature(),
                                               getFactory());
        }
        return genericInfo; 
    }
    //获取该类的注解,本地实现,详见getAnnotation()
    native byte[] getRawAnnotations();
    //获取常量池
    native ConstantPool getConstantPool();
    //获取所有字段信息,可根据参数获取相应访问权限类型字段————————方法1
    private Field[] privateGetDeclaredFields(boolean publicOnly) {
       //只获取该类声明的字段(所有权限类型的),其父类、父接口中声明的并没有
    }
    //类似上面方法,但是返回的是public类型字段,且包括父类、父接口中声明定义的
    //要学会看方法名字,根据英文意思大概能知道方法意义——————————方法2
    private Field[] privateGetPublicFields(Set<Class<?>> traversedInterfaces){
    //有反射的缓存数据,则直接获取后返回
       //若没有,则通过上面方法获取(参数置为true)
       //还要加上其父类以及父接口中声明的公共字段
    }
    private static void addAll(Collection<Field> c, Field[] o) {
        for (int i = 0; i < o.length; i++) {
            c.add(o[i]);
        }
    }
    //类似方法1
    private Constructor<T>[] privateGetDeclaredConstructors(boolean publicOnly) {
       ......
    }
    //类似方法1
    private Method[] privateGetDeclaredMethods(boolean publicOnly) {
        ......
    }
    //方法数组类
    static class MethodArray {
        private Method[] methods;
        private int length;

        MethodArray() {
            methods = new Method[20];
            length = 0;
        }

        void add(Method m) {
            if (length == methods.length) {
                methods = Arrays.copyOf(methods, 2 * methods.length);
            }
            methods[length++] = m;
        }

        void addAll(Method[] ma) {
            for (int i = 0; i < ma.length; i++) {
                add(ma[i]);
            }
        }

        void addAll(MethodArray ma) {
            for (int i = 0; i < ma.length(); i++) {
                add(ma.get(i));
            }
        }

        void addIfNotPresent(Method newMethod) {
            for (int i = 0; i < length; i++) {
                Method m = methods[i];
                if (m == newMethod || (m != null && m.equals(newMethod))) {
                    return;
                }
            }
            add(newMethod);
        }

        void addAllIfNotPresent(MethodArray newMethods) {
           ......
        }

        int length() {
            return length;
        }

        Method get(int i) {
            return methods[i];
        }

        void removeByNameAndSignature(Method toRemove) {
            ......
        }

        void compactAndTrim() {
           ......
        }

        Method[] getArray() {
            return methods;
        }
    }
    //类似方法2
    private Method[] privateGetPublicMethods() {
        ......
    }
    //根据字段名称获取fields中字段信息————————方法3
    private static Field searchFields(Field[] fields, String name) {
    }
    //只获取public字段————————方法4
    private Field getField0(String name) throws NoSuchFieldException {
       Field res;
        // 首先,在本类公共字段中搜索获取同名字段
        if ((res = searchFields(privateGetDeclaredFields(true), name)) != null) {
            return res;
        }
        // 若无,则搜索父接口同名字段,递归调用
        Class<?>[] interfaces = getInterfaces();
        for (int i = 0; i < interfaces.length; i++) {
            Class<?> c = interfaces[i];
            if ((res = c.getField0(name)) != null) {
                return res;
            }
        }
        // 若仍无,判断该类为非接口类型,获取父类同名字段,递归调用
        if (!isInterface()) {
            Class<?> c = getSuperclass();
            if (c != null) {
                if ((res = c.getField0(name)) != null) {
                    return res;
                }
            }
        }
        //都无,则返回空
        return null;
    }
    //类似方法3
    private static Method searchMethods(Method[] methods,
                                        String name,
                                        Class<?>[] parameterTypes)
    {
        ......
    }
    //类似方法4
    private Method getMethod0(String name, Class<?>[] parameterTypes) {
      ......
    }
    //类似方法4
    private Constructor<T> getConstructor0(Class<?>[] parameterTypes,
                                        int which) throws NoSuchMethodException
    {
    }
    //辅助,判断数组是否相等
    private static boolean arrayContentsEq(Object[] a1, Object[] a2) {

    }
    //复制字段数组信息
    private static Field[] copyFields(Field[] arg) {
        Field[] out = new Field[arg.length];
        ReflectionFactory fact = getReflectionFactory();
        for (int i = 0; i < arg.length; i++) {
            out[i] = fact.copyField(arg[i]);
        }
        return out;
    }
    //复制方法数组信息
    private static Method[] copyMethods(Method[] arg) {
        Method[] out = new Method[arg.length];
        ReflectionFactory fact = getReflectionFactory();
        for (int i = 0; i < arg.length; i++) {
            out[i] = fact.copyMethod(arg[i]);
        }
        return out;
    }
    //复制构造器数组信息
    private static <U> Constructor<U>[] copyConstructors(Constructor<U>[] arg) {
        Constructor<U>[] out = arg.clone();
        ReflectionFactory fact = getReflectionFactory();
        for (int i = 0; i < out.length; i++) {
            out[i] = fact.copyConstructor(out[i]);
        }
        return out;
    }
    //以下四个,为获取本类所有声明的字段/方法/构造器/类
    private native Field[]       getDeclaredFields0(boolean publicOnly);
    private native Method[]      getDeclaredMethods0(boolean publicOnly);
    private native Constructor<T>[] getDeclaredConstructors0(boolean publicOnly);
    private native Class<?>[]   getDeclaredClasses0();
    //输出类型数组各个名称
    private static String        argumentTypesToString(Class<?>[] argTypes) {
       .......
    }
    private static final long serialVersionUID = 3206093459760846163L;
    //ObjectStreamField:序列化的对象中成员属性的元数据信息
    private static final ObjectStreamField[] serialPersistentFields =
        new ObjectStreamField[0];
    //获取该类的断言状态,类的断言状态可通过类的ClassLoader设置
    public boolean desiredAssertionStatus() {
       ......
    }
    //上面方法的本地实现
    private static native boolean desiredAssertionStatus0(Class<?> clazz);
    //判断是否是枚举类型
    public boolean isEnum() {
        return (this.getModifiers() & ENUM) != 0 &&
        this.getSuperclass() == java.lang.Enum.class;
    }
    private static ReflectionFactory getReflectionFactory() {
    }
    //反射工厂,可以通过可个工厂对类的元数据进行操作,比如新建一个构造器、方法等
    private static ReflectionFactory reflectionFactory;
    //系统属性是否初始化
    private static boolean initted = false;
    //判断系统属性是否已经初始化,若已经初始化,直接返回,否则初始化
    private static void checkInitted() {
        if (initted) return;
        AccessController.doPrivileged(new PrivilegedAction<Void>() {
                public Void run() {
                    ......
                }
    }
    //如果,此类为枚举类,返回其中的枚举值,否则返回空
    public T[] getEnumConstants() {
        T[] values = getEnumConstantsShared();
        return (values != null) ? values.clone() : null;
    }
    //如果此类为枚举类,返回其中的枚举值,否则返回空
    T[] getEnumConstantsShared() {
         ......
    }
    //枚举值
    private volatile transient T[] enumConstants = null;
    //将枚举转化为map<String, T> String是每个枚举的name属性
    Map<String, T> enumConstantDirectory() {
       if (enumConstantDirectory == null) {//若缓存中为空
            T[] universe = getEnumConstantsShared();//获取所有枚举值
            if (universe == null)//为空则抛出异常
                throw new IllegalArgumentException(
                    getName() + " is not an enum type");
            Map<String, T> m = new HashMap<>(2 * universe.length);
            for (T constant : universe)//遍历存储
                m.put(((Enum<?>)constant).name(), constant);
            enumConstantDirectory = m;
        }
        return enumConstantDirectory;
    }
    private volatile transient Map<String, T> enumConstantDirectory = null;
    //强制转换,如实例为null或不是实例对象,且强制转换不成功,抛出异常
    public T cast(Object obj) {
        if (obj != null && !isInstance(obj))
            throw new ClassCastException(cannotCastMsg(obj));
        return (T) obj;//只是简单的进行强制转换
    }
    //无法强转的报错信息
    private String cannotCastMsg(Object obj) {
        return "Cannot cast " + obj.getClass().getName() + " to " + getName();
    }
    //将调用这个方法的class对象转换成由clazz参数所表示的class对象的某个子类
    //可参考:http://blog.csdn.net/csywwx2008/article/details/17641405
    public <U> Class<? extends U> asSubclass(Class<U> clazz) {
        if (clazz.isAssignableFrom(this))
            return (Class<? extends U>) this;
        else
            throw new ClassCastException(this.toString());
    }
    //获得参数对应的注解对象信息
    public <A extends Annotation> A getAnnotation(Class<A> annotationClass) {
        if (annotationClass == null)
            throw new NullPointerException();

        initAnnotationsIfNecessary();
        return (A) annotations.get(annotationClass);
    }
    //判断该注解类型是否是在该类上(有该注解)
    public boolean isAnnotationPresent(
        Class<? extends Annotation> annotationClass) {
        if (annotationClass == null)
            throw new NullPointerException();

        return getAnnotation(annotationClass) != null;
    }
    //获取该类上所有注解(包括继承),无,则返回长度为零的注解数组
    public Annotation[] getAnnotations() {
        initAnnotationsIfNecessary();
        return AnnotationParser.toArray(annotations);
    }
    //获取该类上所有的声明的注解(不包括继承的),无,则返回长度为零的注解数组
    public Annotation[] getDeclaredAnnotations()  {
        initAnnotationsIfNecessary();
        return AnnotationParser.toArray(declaredAnnotations);
    }
    private transient Map<Class<? extends Annotation>, Annotation> annotations;
    private transient Map<Class<? extends Annotation>, Annotation> declaredAnnotations;
   //类似classRedefinedCount,最后一次注解被定义的个数
    private  transient int lastAnnotationsRedefinedCount = 0;
    //在类被反射重新定义的时候,清除缓存的注解信息
    private void clearAnnotationCachesOnClassRedefinition() {
        if (lastAnnotationsRedefinedCount != classRedefinedCount) {//二者不相等,说明类有被重新定义
            annotations = declaredAnnotations = null;//清空信息
            lastAnnotationsRedefinedCount = classRedefinedCount;
        }
    }
    //初始化类的注解(缓存信息:annotations和declaredAnnotations)
    private synchronized void initAnnotationsIfNecessary() {
        ......
    }
    //注解类型信息缓存
    @SuppressWarnings("UnusedDeclaration")
    private volatile transient AnnotationType annotationType;

    boolean casAnnotationType(AnnotationType oldType, AnnotationType newType) {
        return Atomic.casAnnotationType(this, oldType, newType);
    }

    AnnotationType getAnnotationType() {
        return annotationType;
    }
    transient ClassValue.ClassValueMap classValueMap;
}

1.关于反射工厂ReflectionFactory,是一个很破坏安全的类:

public class Test {
    private Test(){
        System.out.println("test");
    }
    public void say(){
        System.out.println("hello world");
    }
}//按理说,Test这个类只有私有构造器,外部类不能实例化,也就不能在外调用say方法
public class Main{
    private static final ReflectionFactory reflectionFactory = (ReflectionFactory) AccessController
            .doPrivileged(new ReflectionFactory.GetReflectionFactoryAction());
    public static void main(String[] args) throws Exception{
        Constructor<Test> constr = reflectionFactory.newConstructorForSerialization(Test.class, Object.class.getConstructor(new Class[0]));
        Test test = constr.newInstance(new Object[0]);
        test.say();
    }
}
/**
 * 然而事实,却是可以通过ReflectionFactory这个反射工厂新建一个Test的构造器,而后
 * 通过newInstance获取其实例,进而访问其成员方法,这显然是一种对访问权限的破坏
 */

猜你喜欢

转载自blog.csdn.net/a327369238/article/details/54933115