栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

JDK1.8源码学习--lang包(Class)

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

JDK1.8源码学习--lang包(Class)

前言

 


月是一轮明镜,晶莹剔透,代表着一张白纸(啥也不懂)

央是一片海洋,海乃百川,代表着一块海绵(吸纳万物)

泽是一柄利剑,千锤百炼,代表着千百锤炼(输入输出)

月央泽,学习的一种过程,从白纸->吸收各种知识->不断输入输出变成自己的内容

希望大家一起坚持这个过程,也同样希望大家最终都能从零到零,把知识从薄变厚,再由厚变薄!

一.Class的作用:

        直接看源码注释(我的翻译可能不太准,如果道友们有更棒的理解,可以留言或者私信)

 

二.Class的类图:

            a).Type,这个接口确定整个java语言中的类型,详情请点击下面链接

                  ......(假装这个是链接,以后补充)

            b).Secializable,这个接口是可为实现的对象进行序列化,详情请点击下面链接
                  ......(假装这个是链接,以后补充)

            c).GenericDeclaration,这个接口是所有声明类型变量的实体的通用接口,详情请点击下面链接
                  ......(假装这个是链接,以后补充)

            d).AnnotatedElement,这个接口是表示当前在VM中运行的程序带注解的元素,详情请点击下面链接
                  ......(假装这个是链接,以后补充)

 三.成员变量:  
    //表示注解的十六进制
    private static final int ANNOTATION= 0x00002000;
    //枚举的十六进制
    private static final int ENUM      = 0x00004000;
    //合成类的十六进制表示
    private static final int SYNTHETIC = 0x00001000;

    //缓存构造器
    private volatile transient Constructor cachedConstructor;
    //新的实例调用者缓存
    private volatile transient Class       newInstanceCallerCache;
 
    //缓存名字以减少调用VM的次数
    private transient String name;

 // Initialized in JVM not by private constructor
    // This field is filtered from reflection access, i.e. getDeclaredField
    // will throw NoSuchFieldException
    //在JVM初始化而不是私有的构造函数
    //该字段从反射访问中过滤,即 getDeclaredField 将抛出 NoSuchFieldException
    private final ClassLoader classLoader;

   
    //内域为空时返回保护域
    private static java.security.ProtectionDomain allPermDomain;

 // Caches for certain reflective results
    //是否使用缓存
    private static boolean useCaches = true;

    private volatile transient SoftReference> reflectionData;

    // Incremented by the VM on each call to JVM TI RedefineClasses()
    // that redefines this class or a superclass.
    //VM 在每次调用重新定义此类或超类的 JVM TI RedefineClasses() 时递增
    private volatile transient int classRedefinedCount = 0;

 // Generic info repository; lazily initialized
    //通用信息存储库;延迟初始化
    private volatile transient ClassRepository genericInfo;

     //在类描述符写入流的初始时间生成一个新句柄。未来对类描述符的引用被写为对初始类描述符实例的引用
    private static final ObjectStreamField[] serialPersistentFields =
        new ObjectStreamField[0];

  //反射工厂类
    private static ReflectionFactory reflectionFactory;

  // To be able to query system properties as soon as they're available
    //能够在系统属性可用时立即查询
    private static boolean initted = false;

     //枚举常量
    private volatile transient T[] enumConstants = null;

    //枚举常量目录
    private volatile transient Map enumConstantDirectory = null;

     //注解缓存
    private volatile transient AnnotationData annotationData;

     //注解类型缓存其内部 (AnnotationType) 形式
    private volatile transient AnnotationType annotationType;

 //与此类有关的用户定义值的后备存储。由 ClassValue 类维护
    transient ClassValue.ClassValueMap classValueMap;
四.内部类: 

                EnclosingMethodInfo:

//封闭的方法信息
    private final static class EnclosingMethodInfo {
        //封闭的Class对象
        private Class enclosingClass;
        //名称
        private String name;
        //描述符
        private String descriptor;

        private EnclosingMethodInfo(Object[] enclosingInfo) {
            if (enclosingInfo.length != 3)
                throw new InternalError("Malformed enclosing method information");
            try {
                // The array is expected to have three elements:
                //该数组预计具有三个元素:
                // the immediately enclosing class
                //直接封闭的类
                enclosingClass = (Class) enclosingInfo[0];
                assert(enclosingClass != null);

                // the immediately enclosing method or constructor's
                // name (can be null).
                //直接封闭的方法或构造函数的名称(可以为 null)
                name            = (String)   enclosingInfo[1];

                // the immediately enclosing method or constructor's
                // descriptor (null iff name is).
                //直接封闭的方法或构造函数的描述符(如果名称为空,则为空
                descriptor      = (String)   enclosingInfo[2];
                assert((name != null && descriptor != null) || name == descriptor);
            } catch (ClassCastException cce) {
                throw new InternalError("Invalid type in enclosing method information", cce);
            }
        }

        boolean isPartial() {
            return enclosingClass == null || name == null || descriptor == null;
        }

        boolean isConstructor() { return !isPartial() && "".equals(name); }

        boolean isMethod() { return !isPartial() && !isConstructor() && !"".equals(name); }

        Class getEnclosingClass() { return enclosingClass; }

        String getName() { return name; }

        String getDescriptor() { return descriptor; }

    }

                Atomic:

 
    private static class Atomic {
        // initialize Unsafe machinery here, since we need to call Class.class instance method
        // and have to avoid calling it in the static initializer of the Class class...
        //在这里初始化 Unsafe 机器,
        // 因为我们需要调用 Class.class 实例方法并且必须避免在 Class 类的静态初始化器中调用它......
        private static final Unsafe unsafe = Unsafe.getUnsafe();
        // offset of Class.reflectionData instance field
        //Class.reflectionData 实例字段的偏移量
        private static final long reflectionDataOffset;
        // offset of Class.annotationType instance field
        //Class.annotationType 实例字段的偏移量
        private static final long annotationTypeOffset;
        // offset of Class.annotationData instance field
        //Class.annotationData 实例字段的偏移量
        private static final long annotationDataOffset;

        static {
            //获得Class的信息
            Field[] fields = Class.class.getDeclaredFields0(false); // bypass caches
            //查找出反射数据偏移量
            reflectionDataOffset = objectFieldOffset(fields, "reflectionData");
            //查找出注解类型偏移量
            annotationTypeOffset = objectFieldOffset(fields, "annotationType");
            //查找出注解数据偏移量
            annotationDataOffset = objectFieldOffset(fields, "annotationData");
        }

        private static long objectFieldOffset(Field[] fields, String fieldName) {
            //遍历查找是否存在
            Field field = searchFields(fields, fieldName);
            if (field == null) {
                throw new Error("No " + fieldName + " field found in java.lang.Class");
            }
            //存在之后直接通过unsafe来调用查找
            return unsafe.objectFieldOffset(field);
        }
        
        //新老反射数据是否可以交换
        static  boolean casReflectionData(Class clazz,
                                             SoftReference> oldData,
                                             SoftReference> newData) {
            
            return unsafe.compareAndSwapObject(clazz, reflectionDataOffset, oldData, newData);
        }

        // //新老注解类型是否可以交换
        static  boolean casAnnotationType(Class clazz,
                                             AnnotationType oldType,
                                             AnnotationType newType) {
            return unsafe.compareAndSwapObject(clazz, annotationTypeOffset, oldType, newType);
        }

        //新老注解数据是否可以交换
        static  boolean casAnnotationData(Class clazz,
                                             AnnotationData oldData,
                                             AnnotationData newData) {
            return unsafe.compareAndSwapObject(clazz, annotationDataOffset, oldData, newData);
        }
    }

                Reflectiondata:

 // reflection data that might get invalidated when JVM TI RedefineClasses() is called
    //调用 JVM TI RedefineClasses() 时可能会失效的反射数据
    private static class ReflectionData {
        volatile Field[] declaredFields;
        volatile Field[] publicFields;
        volatile Method[] declaredMethods;
        volatile Method[] publicMethods;
        volatile Constructor[] declaredConstructors;
        volatile Constructor[] publicConstructors;
        // Intermediate results for getFields and getMethods
       // getFields 和 getMethods 的中间结果
        volatile Field[] declaredPublicFields;
        volatile Method[] declaredPublicMethods;
        volatile Class[] interfaces;

        // Value of classRedefinedCount when we created this ReflectionData instance
        //当我们创建这个 ReflectionData 实例时 classRedefinedCount 的值
        final int redefinedCount;

        ReflectionData(int redefinedCount) {
            this.redefinedCount = redefinedCount;
        }
    }

                MethodArray:

   static class MethodArray {
        // Don't add or remove methods except by add() or remove() calls.
        //除了 add() 或 remove() 调用之外,不要添加或删除方法
        private Method[] methods;
        private int length;
        private int defaults;
        //默认方法数组容量为20
        MethodArray() {
            this(20);
        }

        MethodArray(int initialSize) {
            if (initialSize < 2)
                throw new IllegalArgumentException("Size should be 2 or more");

            methods = new Method[initialSize];
            length = 0;
            defaults = 0;
        }


        boolean hasDefaults() {
            return defaults != 0;
        }

        void add(Method m) {

            //如果长度等于数组长度,扩容两倍
            if (length == methods.length) {
                methods = Arrays.copyOf(methods, 2 * methods.length);
            }
            //没有直接往后加,长度length+1
            methods[length++] = m;
            //方法不为空,并且方法是默认的
            //defaults++
            if (m != null && m.isDefault())
                defaults++;
        }

        //把方法中的数组全部加进去
        void addAll(Method[] ma) {
            for (int i = 0; i < ma.length; i++) {
                add(ma[i]);
            }
        }

        //将MethodArray中全部加进去
        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) {
            for (int i = 0; i < newMethods.length(); i++) {
                Method m = newMethods.get(i);
                if (m != null) {
                    addIfNotPresent(m);
                }
            }
        }

        
        void addInterfaceMethods(Method[] methods) {
            for (Method candidate : methods) {
                //不是静态方法就加入
                if (!Modifier.isStatic(candidate.getModifiers())) {
                    add(candidate);
                }
            }
        }

        int length() {
            return length;
        }

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

        //返回第一个不为空的方法.如果没有则返回null
        Method getFirst() {
            for (Method m : methods)
                if (m != null)
                    return m;
            return null;
        }

        //通过名字和描述符来删除
        void removeByNameAndDescriptor(Method toRemove) {
            for (int i = 0; i < length; i++) {
                Method m = methods[i];
                if (m != null && matchesNameAndDescriptor(m, toRemove)) {
                    remove(i);
                }
            }
        }

        //删除不为null并且是默认的方法
        private void remove(int i) {
            if (methods[i] != null && methods[i].isDefault())
                defaults--;
            methods[i] = null;
        }

        //通过名字和描述符来匹配
        private boolean matchesNameAndDescriptor(Method m1, Method m2) {
            //返回类型,参数类型,方法签名
            //名字必须要interned
            return m1.getReturnType() == m2.getReturnType() &&
                   m1.getName() == m2.getName() && // name is guaranteed to be interned
                   arrayContentsEq(m1.getParameterTypes(),
                           m2.getParameterTypes());
        }

        //将数组中的null去掉
        void compactAndTrim() {
            int newPos = 0;
            // Get rid of null slots
            for (int pos = 0; pos < length; pos++) {
                Method m = methods[pos];
                if (m != null) {
                    if (pos != newPos) {
                        methods[newPos] = m;
                    }
                    newPos++;
                }
            }
            if (newPos != methods.length) {
                methods = Arrays.copyOf(methods, newPos);
            }
        }

        
        void removeLessSpecifics() {
            if (!hasDefaults())
                return;

            for (int i = 0; i < length; i++) {
                Method m = get(i);
                if  (m == null || !m.isDefault())
                    continue;

                for (int j  = 0; j < length; j++) {
                    if (i == j)
                        continue;

                    Method candidate = get(j);
                    if (candidate == null)
                        continue;

                    if (!matchesNameAndDescriptor(m, candidate))
                        continue;

                    if (hasMoreSpecificClass(m, candidate))
                        remove(j);
                }
            }
        }

        Method[] getArray() {
            return methods;
        }

        // Returns true if m1 is more specific than m2
        //如果 m1 比 m2 更具体,则返回 true
        static boolean hasMoreSpecificClass(Method m1, Method m2) {
            Class m1Class = m1.getDeclaringClass();
            Class m2Class = m2.getDeclaringClass();
            return m1Class != m2Class && m2Class.isAssignableFrom(m1Class);
        }
    }

                Annotationdata:

 // annotation data that might get invalidated when JVM TI RedefineClasses() is called
    //调用 JVM TI RedefineClasses() 时可能会失效的注解数据
    private static class AnnotationData {
        //注解
        final Map, Annotation> annotations;
        //默认注解
        final Map, Annotation> declaredAnnotations;

        // Value of classRedefinedCount when we created this AnnotationData instance
        //当我们创建这个 AnnotationData 实例时 classRedefinedCount 的值
        final int redefinedCount;

        AnnotationData(Map, Annotation> annotations,
                       Map, Annotation> declaredAnnotations,
                       int redefinedCount) {
            this.annotations = annotations;
            this.declaredAnnotations = declaredAnnotations;
            this.redefinedCount = redefinedCount;
        }
    }
五.构造方法:   
    private Class(ClassLoader loader) {
        // Initialize final field for classLoader.  The initialization value of non-null
        // prevents future JIT optimizations from assuming this final field is null.
        //1.初始化 classLoader 的 final 字段。非空的初始化值
        //2.防止未来的 JIT 优化假设这个最终字段为空
        classLoader = loader;
    }
六.内部方法:

                toString()

   
    public String toString() {
        return (isInterface() ? "interface " : (isPrimitive() ? "" : "class "))
            + getName();
    }

                toGenericString()

   
    public String toGenericString() {
        //判断是否是私有的
        if (isPrimitive()) {
            return toString();
        } else {
            StringBuilder sb = new StringBuilder();

            // Class modifiers are a superset of interface modifiers
            //是否有有修饰符
            int modifiers = getModifiers() & Modifier.classModifiers();
            if (modifiers != 0) {
                sb.append(Modifier.toString(modifiers));
                sb.append(' ');
            }

            if (isAnnotation()) {
                sb.append('@');
            }
            if (isInterface()) { // Note: all annotation types are interfaces
                sb.append("interface");
            } else {
                if (isEnum())
                    sb.append("enum");
                else
                    sb.append("class");
            }
            sb.append(' ');
            sb.append(getName());
            //获取参数类型
            TypeVariable[] typeparms = getTypeParameters();
            if (typeparms.length > 0) {
                boolean first = true;
                sb.append('<');
                for(TypeVariable typeparm: typeparms) {
                    if (!first)
                        sb.append(',');
                    //获取参数名称
                    sb.append(typeparm.getTypeName());
                    first = false;
                }
                sb.append('>');
            }

            return sb.toString();
        }
    }

                forName()

 
    @CallerSensitive
    public static Class forName(String className)
                throws ClassNotFoundException {
        Class caller = Reflection.getCallerClass();
        return forName0(className, true, ClassLoader.getClassLoader(caller), caller);
    }

  
    @CallerSensitive
    public static Class forName(String name, boolean initialize,
                                   ClassLoader loader)
        throws ClassNotFoundException
    {
        Class caller = null;
        //获取安全管理器
        SecurityManager sm = System.getSecurityManager();
        if (sm != null) {
            // Reflective call to get caller class is only needed if a security manager
            // is present.  Avoid the overhead of making this call otherwise.
            //仅当存在安全管理器时才需要反射调用以获取调用者类。避免进行此调用的开销
            caller = Reflection.getCallerClass();
            if (sun.misc.VM.isSystemDomainLoader(loader)) {
                ClassLoader ccl = ClassLoader.getClassLoader(caller);
                if (!sun.misc.VM.isSystemDomainLoader(ccl)) {
                    sm.checkPermission(
                        SecurityConstants.GET_CLASSLOADER_PERMISSION);
                }
            }
        }
        return forName0(name, initialize, loader, caller);
    }

                newInstance()

    @CallerSensitive
    public T newInstance()
        throws InstantiationException, IllegalAccessException
    {
        if (System.getSecurityManager() != null) {
            //检查成员访问权限
            checkMemberAccess(Member.PUBLIC, Reflection.getCallerClass(), false);
        }

        // NOTE: the following code may not be strictly correct under
        // the current Java memory model.
        //以下代码在当前Java内存模型下可能不严格正确
        // Constructor lookup
        if (cachedConstructor == null) {
            if (this == Class.class) {
                throw new IllegalAccessException(
                    "Can not call newInstance() on the Class for java.lang.Class"
                );
            }
            try {
                Class[] empty = {};
                final Constructor c = getConstructor0(empty, Member.DECLARED);
                // Disable accessibility checks on the constructor
                // since we have to do the security check here anyway
                // (the stack depth is wrong for the Constructor's
                // security check to work)
                //禁用对构造函数的可访问性检查,
                // 因为无论如何我们都必须在此处进行安全检查(堆栈深度错误,构造函数的安全检查无法正常工作)
                java.security.AccessController.doPrivileged(
                    new java.security.PrivilegedAction() {
                        public Void run() {
                                c.setAccessible(true);
                                return null;
                            }
                        });
                cachedConstructor = c;
            } catch (NoSuchMethodException e) {
                throw (InstantiationException)
                    new InstantiationException(getName()).initCause(e);
            }
        }
        Constructor tmpConstructor = cachedConstructor;
        // Security check (same as in java.lang.reflect.Constructor)
        int modifiers = tmpConstructor.getModifiers();

        //检查成员访问权限
        if (!Reflection.quickCheckMemberAccess(this, modifiers)) {
            Class caller = Reflection.getCallerClass();
            if (newInstanceCallerCache != caller) {
                Reflection.ensureMemberAccess(caller, this, null, modifiers);
                newInstanceCallerCache = caller;
            }
        }
        // Run constructor
        try {
            return tmpConstructor.newInstance((Object[])null);
        } catch (InvocationTargetException e) {
            Unsafe.getUnsafe().throwException(e.getTargetException());
            // Not reached
            return null;
        }
    }

                判断类方法:

  
    public native boolean isInstance(Object obj);

  
    public native boolean isInstance(Object obj);


    
    public native boolean isAssignableFrom(Class cls);


    
    public native boolean isInterface();


    
    public native boolean isArray();


    
    public native boolean isPrimitive();

    
    public boolean isAnnotation() {
        return (getModifiers() & ANNOTATION) != 0;
    }

    
    public boolean isSynthetic() {
        return (getModifiers() & SYNTHETIC) != 0;
    }

                获取类方法:

  
    public String getName() {
        String name = this.name;
        if (name == null)
            this.name = name = getName0();
        return name;
    }


    @CallerSensitive
    public ClassLoader getClassLoader() {
        ClassLoader cl = getClassLoader0();
        if (cl == null)
            return null;
        SecurityManager sm = System.getSecurityManager();
        if (sm != null) {
            ClassLoader.checkClassLoaderPermission(cl, Reflection.getCallerClass());
        }
        return cl;
    }


    
    @SuppressWarnings("unchecked")
    public TypeVariable>[] getTypeParameters() {
        ClassRepository info = getGenericInfo();
        if (info != null)
            return (TypeVariable>[])info.getTypeParameters();
        else
            return (TypeVariable>[])new TypeVariable[0];
    }


    
    public native Class getSuperclass();


    
    public Type getGenericSuperclass() {
        ClassRepository info = getGenericInfo();
        if (info == null) {
            return getSuperclass();
        }

        // Historical irregularity:
        // Generic signature marks interfaces with superclass = Object
        // but this API returns null for interfaces
        if (isInterface()) {
            return null;
        }

        return info.getSuperclass();
    }

    
    public Package getPackage() {
        return Package.getPackage(this);
    }


    
    public Class[] getInterfaces() {
        ReflectionData rd = reflectionData();
        if (rd == null) {
            // no cloning required
            return getInterfaces0();
        } else {
            Class[] interfaces = rd.interfaces;
            if (interfaces == null) {
                interfaces = getInterfaces0();
                rd.interfaces = interfaces;
            }
            // defensively copy before handing over to user code
            //在移交给用户代码之前防御性地复制
            return interfaces.clone();
        }
    }


    
    public Type[] getGenericInterfaces() {
        ClassRepository info = getGenericInfo();
        return (info == null) ?  getInterfaces() : info.getSuperInterfaces();
    }


    
    @CallerSensitive
    public Method getEnclosingMethod() throws SecurityException {
        EnclosingMethodInfo enclosingInfo = getEnclosingMethodInfo();

        if (enclosingInfo == null)
            return null;
        else {
            if (!enclosingInfo.isMethod())
                return null;

            MethodRepository typeInfo = MethodRepository.make(enclosingInfo.getDescriptor(),
                                                              getFactory());
            Class   returnType       = toClass(typeInfo.getReturnType());
            Type []    parameterTypes   = typeInfo.getParameterTypes();
            Class[] parameterClasses = new Class[parameterTypes.length];

            // Convert Types to Classes; returned types *should*
            // be class objects since the methodDescriptor's used
            // don't have generics information
            for(int i = 0; i < parameterClasses.length; i++)
                parameterClasses[i] = toClass(parameterTypes[i]);

            // Perform access check
            Class enclosingCandidate = enclosingInfo.getEnclosingClass();
            enclosingCandidate.checkMemberAccess(Member.DECLARED,
                                                 Reflection.getCallerClass(), true);
            
            for(Method m: enclosingCandidate.getDeclaredMethods()) {
                if (m.getName().equals(enclosingInfo.getName()) ) {
                    Class[] candidateParamClasses = m.getParameterTypes();
                    if (candidateParamClasses.length == parameterClasses.length) {
                        boolean matches = true;
                        for(int i = 0; i < candidateParamClasses.length; i++) {
                            if (!candidateParamClasses[i].equals(parameterClasses[i])) {
                                matches = false;
                                break;
                            }
                        }

                        if (matches) { // finally, check return type
                            if (m.getReturnType().equals(returnType) )
                                return m;
                        }
                    }
                }
            }

            throw new InternalError("Enclosing method not found");
        }
    }


   

    
    @CallerSensitive
    public Constructor getEnclosingConstructor() throws SecurityException {
        EnclosingMethodInfo enclosingInfo = getEnclosingMethodInfo();

        if (enclosingInfo == null)
            return null;
        else {
            if (!enclosingInfo.isConstructor())
                return null;

            ConstructorRepository typeInfo = ConstructorRepository.make(enclosingInfo.getDescriptor(),
                                                                        getFactory());
            Type []    parameterTypes   = typeInfo.getParameterTypes();
            Class[] parameterClasses = new Class[parameterTypes.length];

            // Convert Types to Classes; returned types *should*
            // be class objects since the methodDescriptor's used
            // don't have generics information
            //将类型转换为类;返回的类型应该是类对象,因为使用的 methodDescriptor 没有泛型信息
            for(int i = 0; i < parameterClasses.length; i++)
                parameterClasses[i] = toClass(parameterTypes[i]);

            // Perform access check
            //执行访问检查
            Class enclosingCandidate = enclosingInfo.getEnclosingClass();
            enclosingCandidate.checkMemberAccess(Member.DECLARED,
                                                 Reflection.getCallerClass(), true);
            
            for(Constructor c: enclosingCandidate.getDeclaredConstructors()) {
                Class[] candidateParamClasses = c.getParameterTypes();
                if (candidateParamClasses.length == parameterClasses.length) {
                    boolean matches = true;
                    for(int i = 0; i < candidateParamClasses.length; i++) {
                        if (!candidateParamClasses[i].equals(parameterClasses[i])) {
                            matches = false;
                            break;
                        }
                    }

                    if (matches)
                        return c;
                }
            }

            throw new InternalError("Enclosing constructor not found");
        }
    }


    
    @CallerSensitive
    public Class getEnclosingClass() throws SecurityException {
        // There are five kinds of classes (or interfaces):
        // a) Top level classes
        // b) Nested classes (static member classes)
        // c) Inner classes (non-static member classes)
        // d) Local classes (named classes declared within a method)
        // e) Anonymous classes


        // JVM Spec 4.8.6: A class must have an EnclosingMethod
        // attribute if and only if it is a local class or an
        // anonymous class.
        //有五种类(或接口):
        // a)顶级类
        // b)嵌套类(静态成员类)
        // c)内部类(非静态成员类)
        // d)局部类(在方法中声明的命名类)
        // e)匿名类
        // JVM 规范 4.8.6:
        // 当且仅当一个类是本地类或匿名类时,该类必须具有 EnclosureMethod 属性
        EnclosingMethodInfo enclosingInfo = getEnclosingMethodInfo();
        Class enclosingCandidate;

        if (enclosingInfo == null) {
            // This is a top level or a nested class or an inner class (a, b, or c)
            //这是顶级或嵌套类或内部类(a、b 或 c)
            enclosingCandidate = getDeclaringClass();
        } else {
            Class enclosingClass = enclosingInfo.getEnclosingClass();
            // This is a local class or an anonymous class (d or e)
            //他是本地类或匿名类(d 或 e)
            if (enclosingClass == this || enclosingClass == null)
                throw new InternalError("Malformed enclosing method information");
            else
                enclosingCandidate = enclosingClass;
        }

        if (enclosingCandidate != null)
            enclosingCandidate.checkPackageAccess(
                    ClassLoader.getClassLoader(Reflection.getCallerClass()), true);
        return enclosingCandidate;
    }

    
    public String getSimpleName() {
        //首先判断是否是数组
        if (isArray())
            //返回表示数组组件类型的 Class
            return getComponentType().getSimpleName()+"[]";

        //获取底层简单名称
        String simpleName = getSimpleBinaryName();
        if (simpleName == null) { // top level class
            //如果为null,则表示顶层类
            simpleName = getName();
            //去掉包名
            return simpleName.substring(simpleName.lastIndexOf(".")+1); // strip the package name
        }
        // According to JLS3 "Binary Compatibility" (13.1) the binary
        // name of non-package classes (not top level) is the binary
        // name of the immediately enclosing class followed by a '$' followed by:
        // (for nested and inner classes): the simple name.
        // (for local classes): 1 or more digits followed by the simple name.
        // (for anonymous classes): 1 or more digits.
        //根据 JLS3“二进制兼容性”(13.1),
        // 非包类(不是顶级)的二进制名称是紧接其后的类的二进制名称后跟一个 '$':
        // (对于嵌套类和内部类):简单的姓名。 (
        // 对于本地类):1 个或多个数字后跟简单名称。
        // (对于匿名类):1 个或多个数字

        // Since getSimpleBinaryName() will strip the binary name of
        // the immediatly enclosing class, we are now looking at a
        // string that matches the regular expression "$[0-9]*"
        // followed by a simple name (considering the simple of an
        // anonymous class to be the empty string).
        //由于 getSimpleBinaryName() 将剥离直接封闭类的二进制名称,
        // 我们现在查看匹配正则表达式“$[0-9]*”的字符串,后跟一个简单名称(考虑匿名类的简单名称为空字符串
        // Remove leading "$[0-9]*" from the name
        int length = simpleName.length();
        if (length < 1 || simpleName.charAt(0) != '$')
            throw new InternalError("Malformed class name");
        int index = 1;
        while (index < length && isAsciiDigit(simpleName.charAt(index)))
            index++;
        // Eventually, this is the empty string iff this is an anonymous class
       // 最终,如果这是一个匿名类,这是空字符串
        return simpleName.substring(index);
    }

    
    public String getTypeName() {
        //判断是否是数组
        if (isArray()) {
            try {
                Class cl = this;
                //记录是几维数组
                int dimensions = 0;
                while (cl.isArray()) {
                    dimensions++;
                    cl = cl.getComponentType();
                }
                StringBuilder sb = new StringBuilder();
                sb.append(cl.getName());
                for (int i = 0; i < dimensions; i++) {
                    sb.append("[]");
                }
                return sb.toString();
            } catch (Throwable e) {  }
        }
        return getName();
    }



    
    public String getCanonicalName() {
        if (isArray()) {
            //获取数组的类型,然后在获取基础名称
            String canonicalName = getComponentType().getCanonicalName();
            if (canonicalName != null)
                return canonicalName + "[]";
            else
                return null;
        }
        //本地或匿名类 返回null
        if (isLocalOrAnonymousClass())
            return null;
        //获取封闭类
        Class enclosingClass = getEnclosingClass();

        //没有就是顶层类
        if (enclosingClass == null) { // top level class
            //直接获取顶层类名称
            return getName();
        } else {

            String enclosingName = enclosingClass.getCanonicalName();
            if (enclosingName == null)
                return null;
            return enclosingName + "." + getSimpleName();
        }
    }

    
    public boolean isAnonymousClass() {
        return "".equals(getSimpleName());
    }

    
    public boolean isLocalClass() {
        return isLocalOrAnonymousClass() && !isAnonymousClass();
    }

    
    public boolean isMemberClass() {
        return getSimpleBinaryName() != null && !isLocalOrAnonymousClass();
    }


    
    @CallerSensitive
    public Class[] getClasses() {
        //检查成员的访问权限
        checkMemberAccess(Member.PUBLIC, Reflection.getCallerClass(), false);

        // Privileged so this implementation can look at DECLARED classes,
        // something the caller might not have privilege to do.  The code here
        // is allowed to look at DECLARED classes because (1) it does not hand
        // out anything other than public members and (2) public member access
        // has already been ok'd by the SecurityManager.
        //因此此实现可以查看已声明的类,调用者可能无权执行此操作。
        // 允许这里的代码查看 DECLARED 类,
        // 因为 (1) 它不分发公共成员以外的任何东西,并且
        // (2) SecurityManager 已经确定公共成员访问权限

        return java.security.AccessController.doPrivileged(
            new java.security.PrivilegedAction[]>() {
                public Class[] run() {
                    List> list = new ArrayList<>();
                    Class currentClass = Class.this;
                    while (currentClass != null) {
                        Class[] members = currentClass.getDeclaredClasses();
                        for (int i = 0; i < members.length; i++) {
                            if (Modifier.isPublic(members[i].getModifiers())) {
                                list.add(members[i]);
                            }
                        }
                        currentClass = currentClass.getSuperclass();
                    }
                    return list.toArray(new Class[0]);
                }
            });
    }


    
    @CallerSensitive
    public Field[] getFields() throws SecurityException {
        checkMemberAccess(Member.PUBLIC, Reflection.getCallerClass(), true);
        return copyFields(privateGetPublicFields(null));
    }


    
    @CallerSensitive
    public Method[] getMethods() throws SecurityException {
        checkMemberAccess(Member.PUBLIC, Reflection.getCallerClass(), true);
        return copyMethods(privateGetPublicMethods());
    }


    
    @CallerSensitive
    public Constructor[] getConstructors() throws SecurityException {
        checkMemberAccess(Member.PUBLIC, Reflection.getCallerClass(), true);
        return copyConstructors(privateGetDeclaredConstructors(true));
    }


    
    @CallerSensitive
    public Field getField(String name)
        throws NoSuchFieldException, SecurityException {
        checkMemberAccess(Member.PUBLIC, Reflection.getCallerClass(), true);
        Field field = getField0(name);
        if (field == null) {
            throw new NoSuchFieldException(name);
        }
        return field;
    }


    
    @CallerSensitive
    public Method getMethod(String name, Class... parameterTypes)
        throws NoSuchMethodException, SecurityException {
        checkMemberAccess(Member.PUBLIC, Reflection.getCallerClass(), true);
        Method method = getMethod0(name, parameterTypes, true);
        if (method == null) {
            throw new NoSuchMethodException(getName() + "." + name + argumentTypesToString(parameterTypes));
        }
        return method;
    }


    
    @CallerSensitive
    public Constructor getConstructor(Class... parameterTypes)
        throws NoSuchMethodException, SecurityException {
        checkMemberAccess(Member.PUBLIC, Reflection.getCallerClass(), true);
        return getConstructor0(parameterTypes, Member.PUBLIC);
    }


    
    @CallerSensitive
    public Class[] getDeclaredClasses() throws SecurityException {
        checkMemberAccess(Member.DECLARED, Reflection.getCallerClass(), false);
        return getDeclaredClasses0();
    }


    
    @CallerSensitive
    public Field[] getDeclaredFields() throws SecurityException {
        checkMemberAccess(Member.DECLARED, Reflection.getCallerClass(), true);
        return copyFields(privateGetDeclaredFields(false));
    }


    
    @CallerSensitive
    public Method[] getDeclaredMethods() throws SecurityException {
        checkMemberAccess(Member.DECLARED, Reflection.getCallerClass(), true);
        return copyMethods(privateGetDeclaredMethods(false));
    }


    
    @CallerSensitive
    public Constructor[] getDeclaredConstructors() throws SecurityException {
        checkMemberAccess(Member.DECLARED, Reflection.getCallerClass(), true);
        return copyConstructors(privateGetDeclaredConstructors(false));
    }


    
    @CallerSensitive
    public Field getDeclaredField(String name)
        throws NoSuchFieldException, SecurityException {
        checkMemberAccess(Member.DECLARED, Reflection.getCallerClass(), true);
        Field field = searchFields(privateGetDeclaredFields(false), name);
        if (field == null) {
            throw new NoSuchFieldException(name);
        }
        return field;
    }


    
    @CallerSensitive
    public Method getDeclaredMethod(String name, Class... parameterTypes)
        throws NoSuchMethodException, SecurityException {
        checkMemberAccess(Member.DECLARED, Reflection.getCallerClass(), true);
        Method method = searchMethods(privateGetDeclaredMethods(false), name, parameterTypes);
        if (method == null) {
            throw new NoSuchMethodException(getName() + "." + name + argumentTypesToString(parameterTypes));
        }
        return method;
    }


    
    @CallerSensitive
    public Constructor getDeclaredConstructor(Class... parameterTypes)
        throws NoSuchMethodException, SecurityException {
        checkMemberAccess(Member.DECLARED, Reflection.getCallerClass(), true);
        return getConstructor0(parameterTypes, Member.DECLARED);
    }

    
     public InputStream getResourceAsStream(String name) {
        name = resolveName(name);
        ClassLoader cl = getClassLoader0();
        if (cl==null) {
            // A system class.
            return ClassLoader.getSystemResourceAsStream(name);
        }
        return cl.getResourceAsStream(name);
    }

    
    public java.net.URL getResource(String name) {
        name = resolveName(name);
        ClassLoader cl = getClassLoader0();
        if (cl==null) {
            // A system class.
            return ClassLoader.getSystemResource(name);
        }
        return cl.getResource(name);
    }

    
    public java.security.ProtectionDomain getProtectionDomain() {
        //判断是否存在安全管理器
        SecurityManager sm = System.getSecurityManager();
        if (sm != null) {
            sm.checkPermission(SecurityConstants.GET_PD_PERMISSION);
        }
        //获取保护域
        java.security.ProtectionDomain pd = getProtectionDomain0();
        if (pd == null) {
            if (allPermDomain == null) {
                java.security.Permissions perms =
                    new java.security.Permissions();
                perms.add(SecurityConstants.ALL_PERMISSION);
                allPermDomain =
                    new java.security.ProtectionDomain(null, perms);
            }
            pd = allPermDomain;
        }
        return pd;
    }




    //获取可执行类型注释字节
    static byte[] getExecutableTypeAnnotationBytes(Executable ex) {
        return getReflectionFactory().getExecutableTypeAnnotationBytes(ex);
    }
   
    
    public boolean desiredAssertionStatus() {
        ClassLoader loader = getClassLoader();
        // If the loader is null this is a system class, so ask the VM
        //如果 loader 为 null,则这是一个系统类,因此请询问 VM
        if (loader == null)
            return desiredAssertionStatus0(this);

        // If the classloader has been initialized with the assertion
        // directives, ask it. Otherwise, ask the VM.
        //If the classloader has been initialized with the assertion directives, ask it. Otherwise, ask the VM.
        synchronized(loader.assertionLock) {
            if (loader.classAssertionStatus != null) {
                return loader.desiredAssertionStatus(getName());
            }
        }
        return desiredAssertionStatus0(this);
    }

    
    public boolean isEnum() {
        // An enum must both directly extend java.lang.Enum and have
        // the ENUM bit set; classes for specialized enum constants
        // don't do the former.
        //枚举必须直接扩展 java.lang.Enum 并设置 ENUM 位;专门的枚举常量的类不做前者
        return (this.getModifiers() & ENUM) != 0 &&
        this.getSuperclass() == java.lang.Enum.class;
    }


    
    public T[] getEnumConstants() {
        T[] values = getEnumConstantsShared();
        return (values != null) ? values.clone() : null;
    }

    
    T[] getEnumConstantsShared() {
        if (enumConstants == null) {
            if (!isEnum()) return null;
            try {
                final Method values = getMethod("values");
                java.security.AccessController.doPrivileged(
                    new java.security.PrivilegedAction() {
                        public Void run() {
                                values.setAccessible(true);
                                return null;
                            }
                        });
                @SuppressWarnings("unchecked")
                T[] temporaryConstants = (T[])values.invoke(null);
                enumConstants = temporaryConstants;
            }
            // These can happen when users concoct enum-like classes
            // that don't comply with the enum spec.
            //当用户编造不符合枚举规范的类似枚举的类时,就会发生这些情况
            catch (InvocationTargetException | NoSuchMethodException |
                   IllegalAccessException ex) { return null; }
        }
        return enumConstants;
    }


    
    Map enumConstantDirectory() {
        if (enumConstantDirectory == null) {
            T[] universe = getEnumConstantsShared();
            if (universe == null)
                throw new IllegalArgumentException(
                    getName() + " is not an enum type");
            Map m = new HashMap<>(2 * universe.length);
            for (T constant : universe)
                m.put(((Enum)constant).name(), constant);
            enumConstantDirectory = m;
        }
        return enumConstantDirectory;
    }

    
    @SuppressWarnings("unchecked")
    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();
    }

    
    @SuppressWarnings("unchecked")
    public  Class asSubclass(Class clazz) {
        //判断是否向上转型成功
        if (clazz.isAssignableFrom(this))
            return (Class) this;
        else
            throw new ClassCastException(this.toString());
    }

    
    @SuppressWarnings("unchecked")
    public  A getAnnotation(Class annotationClass) {
        Objects.requireNonNull(annotationClass);

        return (A) annotationData().annotations.get(annotationClass);
    }

    
    @Override
    public boolean isAnnotationPresent(Class annotationClass) {
        return GenericDeclaration.super.isAnnotationPresent(annotationClass);
    }

    
    @Override
    public  A[] getAnnotationsByType(Class annotationClass) {
        Objects.requireNonNull(annotationClass);

        AnnotationData annotationData = annotationData();
        return AnnotationSupport.getAssociatedAnnotations(annotationData.declaredAnnotations,
                                                          this,
                                                          annotationClass);
    }

    
    public Annotation[] getAnnotations() {
        return AnnotationParser.toArray(annotationData().annotations);
    }

    
    @Override
    @SuppressWarnings("unchecked")
    public  A getDeclaredAnnotation(Class annotationClass) {
        Objects.requireNonNull(annotationClass);

        return (A) annotationData().declaredAnnotations.get(annotationClass);
    }

    
    @Override
    public  A[] getDeclaredAnnotationsByType(Class annotationClass) {
        Objects.requireNonNull(annotationClass);

        return AnnotationSupport.getDirectlyAndIndirectlyPresent(annotationData().declaredAnnotations,
                                                                 annotationClass);
    }

    
    public Annotation[] getDeclaredAnnotations()  {
        return AnnotationParser.toArray(annotationData().declaredAnnotations);
    }

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

    AnnotationType getAnnotationType() {
        return annotationType;
    }

    Map, Annotation> getDeclaredAnnotationMap() {
        return annotationData().declaredAnnotations;
    }


    
    public AnnotatedType getAnnotatedSuperclass() {
        if (this == Object.class ||
                isInterface() ||
                isArray() ||
                isPrimitive() ||
                this == Void.TYPE) {
            return null;
        }

        return TypeAnnotationParser.buildAnnotatedSuperclass(getRawTypeAnnotations(), getConstantPool(), this);
    }

    
    public AnnotatedType[] getAnnotatedInterfaces() {
         return TypeAnnotationParser.buildAnnotatedInterfaces(getRawTypeAnnotations(), getConstantPool(), this);
    }
七.总结:   

        Class类中还是有很多地方值得探索,大概率也只是把方法过了一遍,知道怎么一回事,毕竟内容很多,时间很长,或许有一天,到了某一地方,突然发现好像连起来了.这大概很有意思吧.

转载请注明:文章转载自 www.mshxw.com
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号