java.lang.Class

package java.lang;

import java.lang.reflect.Member;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.lang.reflect.Constructor;
import java.lang.reflect.Modifier;
import java.lang.reflect.InvocationTargetException;
import java.lang.ref.SoftReference;
import java.io.InputStream;
import java.io.ObjectStreamClass;
import java.io.ObjectStreamField;
import java.security.AccessController;
import java.security.PrivilegedAction;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.LinkedList;
import java.util.LinkedHashSet;
import java.util.Set;

import sun.misc.Unsafe;
import sun.reflect.Reflection;
import sun.reflect.ReflectionFactory;
import sun.reflect.SignatureIterator;
import sun.security.util.SecurityConstants;


/**
 *
 * java中有两种变量,原始变量和对象,对象又分普通对象,和数组对象
 * 通过类的Class对象可以得到对类或接口的动态描述,这也是反射功能的起始
 *
 * comment by liqiang
 *
 */
public final
class Class implements java.io.Serializable {

    private static native void registerNatives();
    static {
        registerNatives();
    }

    //私有的构造函数,只有虚拟机能创建此对象
    private Class() {}


    /**
     *
     * 返回字符串表示
     *
     */
    public String toString() {
        return (isInterface() ? "interface " : (isPrimitive() ? "" : "class "))
            + getName();
    }


    /**
     *
     * 装载一个类并初始化它
     *
     * @param      className   class的全限定名
     *
     */
    public static Class forName(String className)
                throws ClassNotFoundException {
        return forName0(className, true, ClassLoader.getCallerClassLoader());
    }


    /**
     *
     * 装载此类并返回类对象
     *
     * @param name       类的全限定名
     * @param initialize 是否初始化
     * @param loader     装载此类的ClassLoader
     *
     */
    public static Class forName(String name, boolean initialize,
    ClassLoader loader)
        throws ClassNotFoundException
    {
    //安全检查 
 if (loader == null) {
     SecurityManager sm = System.getSecurityManager();
     if (sm != null) {
     //获得调用者的ClassLoader
  ClassLoader ccl = ClassLoader.getCallerClassLoader();
  if (ccl != null) {
      sm.checkPermission(
   SecurityConstants.GET_CLASSLOADER_PERMISSION);
  }
     }
 }
 
 //如果initialize为false,不进行link,所以不会看到static块的效果
 return forName0(name, initialize, loader);
    }


    /**
     *
     * 装载此类并返回类对象的本地方法
     *
     * @param 类的全限定名
     * @param 是否被初始化
     * @param 装载此类的ClassLoaders
     */
    private static native Class forName0(String name, boolean initialize,
      ClassLoader loader)
 throws ClassNotFoundException;

    /**
     *
     * 创建对象实例
     *
     *
     */
    public Object newInstance()
        throws InstantiationException, IllegalAccessException
    {
    //安全性检查
 if (System.getSecurityManager() != null) {
     checkMemberAccess(Member.PUBLIC, ClassLoader.getCallerClassLoader());
 }
 return newInstance0();
    }

    //得到无参构造函数,获得对象实例
    private Object newInstance0()
        throws InstantiationException, IllegalAccessException
    {
        // NOTE: the following code may not be strictly correct under
        // the current Java memory model.

        // Constructor lookup
        if (cachedConstructor == null) {//缓存的构造函数对象为空
         //如果当前对象是Class类 则抛出异常,因为Class类不能被实例化
            if (this == Class.class) {
                throw new IllegalAccessException(
                    "Can not call newInstance() on the Class for java.lang.Class"
                );
            }
           
            try {
             //声明成final是为了在内部类中使用
             //获得无参的构造函数对象
             //注意newInstance一个实例不需要构造函数为publicd的
                final Constructor c =
                  getConstructor0(new Class[] {}, Member.DECLARED);
                              
                java.security.AccessController.doPrivileged
                    (new java.security.PrivilegedAction() {
                            public Object run() {
                                c.setAccessible(true);
                                return null;
                            }
                        });
               
                //缓存构造函数对象
                cachedConstructor = c;              
            } catch (NoSuchMethodException e) {
                throw new InstantiationException(getName());
            }
        }
       
        //从缓存对象中得到此无参构造函数
        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(3);
            if (newInstanceCallerCache != caller) {
                Reflection.ensureMemberAccess(caller, this, null, modifiers);
                newInstanceCallerCache = caller;
            }
        }
       
        // Run constructor
        try {
         //使用无参的构造函数获得对象实例
            return tmpConstructor.newInstance(null);
        } catch (InvocationTargetException e) {
            Unsafe.getUnsafe().throwException(e.getTargetException());
            // Not reached
            return null;
        }
    }
   
    //缓存的构造函数对象
    private volatile transient Constructor cachedConstructor;
    private volatile transient Class       newInstanceCallerCache;


    /**
     *
     * 此方法是一种实现instanceof操作符的动态方法
     * 他表示当前Class对象是否是obj参数表示的类(接口)或父类(接口)
     * 原始类型的Class对象调用此方法衡为false
     * 数组类型的要求能转换成的返回true注意数组能转换看元素类型和维数,跟长度无关
     * (new String[2]).getClass().isInstance(new String[5])返回真,与长度无关
     *
     *
     * @param   被判断的对象
     */
    public native boolean isInstance(Object obj);


    /**
     *
     * 判断当前Class是否是cls参数的父类或父接口
     *
     * @param cls 被判断的Class对象
     */
    public native boolean isAssignableFrom(Class cls);


    /**
     *
     * 判断当前Class对象是否表示接口
     *
     * @return  <code>true</code> if this object represents an interface;
     *          <code>false</code> otherwise.
     */
    public native boolean isInterface();


    /**
     * Determines if this <code>Class</code> object represents an array class.
     *
     * 判断当前Class对象是否是数组
     *
     * @return  <code>true</code> if this object represents an array class;
     *          <code>false</code> otherwise.
     * @since   JDK1.1
     */
    public native boolean isArray();


    /**
     * 此方法判断Class对象是否表示原始类型
     *
     * 原始类型(primitive type)包括 boolean(1 bit),byte(1 byte),char(2 byte)
     * short(2 byte),int(4 byte),long(8 byte),float(4 byte),double(8 byte)
     *
     * 他们有对应的类的封装形式: Boolean,Byte,Character,Short,Integer,Long,
     * Float,Double,因为在某些情况只能使用对象,所以要将原型封装,比如ArrayList中只能
     * add对象所以如果要添加一个int必须封装成Integer,取出时再通过Integer对象取得int 值
     *
     * 原是类型也有相应描述的Class对象,取得此对象的方法有两种(以int为例):
     * 1 int.class 2 Integer.TYPE
     *
     * 注意虽然void不是原始类型不过存在Void封装类,获得void的Class对象通过void.class Void.TYPE
     *
     */
    public native boolean isPrimitive();

    /**
     *
     * 返回类的名称
     *
     * 例子:
     * 1 对象类型
     * String.class.getName() 返回 "java.lang.String"
     *
     * 2原始类型
     * int.class.getName() 返回 "int"
     *
     * 3数组类型(注意它表示元素方式,和标志维数的方式)
     * (new Object[3]).getClass().getName() 返回 "[Ljava.lang.Object"
     * (new int[3][4][5]).getClass().getName() 返回 "[[[I"
     *
     * 注意
     * a几维就用几个"["表示
     * b数组的元素类型用一个大写字母标志
     * 类或者接口 : L
     * boolean: Z
     * byte: B
     * char: C
     * double: D
     * float: F
     * int: I
     * long: J
     * short: S
     * c 类(接口)在后面显示元素的类的getName,而原是类型不显示
     *
     */
    public String getName() {
      if (name == null)
          name = getName0();
      return name;
    }
 
    // 类名的cache变量
    private transient String name;
    //获得类名的本地方法
    private native String getName0();


    /**
     * 返回此类的ClassLoader
     * 如果此类(例如java.lang.String)是由bootstrap ClassLoader装载的返回null
     * 原始类型返回null
     * 如果Class对象表示的是数组,则获得的ClassLoader是元素的ClassLoader
     * 例如:
     * 1(new Test[10]).getClass().getClassLoader()返回null,因为元素是原始类型
     * 2(new String[10]).getClass().getClassLoader()返回null,因为String
     * 是由bootstrap ClassLoader装载的
     * 3(new Test[10]).getClass().getClassLoader()
     * 返回sun.misc.Launcher$AppClassLoader@e2eec8,Test是自定义的类
     *
     */
    public ClassLoader getClassLoader() {
     //获得当前类的ClassLoader
        ClassLoader cl = getClassLoader0();
       
        if (cl == null)
            return null;
       
        SecurityManager sm = System.getSecurityManager();
        if (sm != null) {         
         //获得调用对类的ClassLoader
            ClassLoader ccl = ClassLoader.getCallerClassLoader();
           
            //如果调用对象的类不是是由bootstrap ClassLoader转载,并且当前对象的类
            //与调用对象的类不是由同一虚拟机装载,且当前对象的ClassLoader不是调用
            //对象的虚拟机的上层(ClassLoader链结构的上层),则进行安全检查
            if (ccl != null && ccl != cl && !cl.isAncestor(ccl)) {
                sm.checkPermission(SecurityConstants.GET_CLASSLOADER_PERMISSION);
            }
        }
       
        return cl;
    }

    // Package-private to allow ClassLoader access
    native ClassLoader getClassLoader0();


    /**  
     *
     * 返回类的父类对象
     *
     * 如果类对象表示Object类,或接口,或原始类型,或void则其父类返回null
     * 如果当前类表示数组则返回Object类的类对象
     *
     * @return the superclass of the class represented by this object.
     */
    public native Class getSuperclass();


    /**
     *
     * 获取当前类的 Package对象
     *
     * @return the package of the class, or null if no package
     *         information is available from the archive or codebase.
     */
    public Package getPackage() {
        return Package.getPackage(this);
    }


    /**
     *
     * 或得类实现的接口列表,或接口继承的接口列表
     * 如果类(接口)没有实现(继承)接口则返回0长度的数组
     * 如果是原始类型返回0长度的数组
     * 数组类型依照其元素
     * 返回的数组顺序跟类(接口)实现(继承)的顺序一致
     *
     */
    public native Class[] getInterfaces();


    /**
     *
     * 如果当前Class表示数组类型,则返回元素类型,如果不是数组类型返回null
     *
     */
    public native Class getComponentType();


    /**
     *
     * 获取类的描述符
     *
     */
    public native int getModifiers();


    /**
     * Gets the signers of this class.
     *
     * @return  the signers of this class, or null if there are no signers.  In
     *   particular, this method returns null if this object represents
     *   a primitive type or void.
     * @since  JDK1.1
     */
    public native Object[] getSigners();
       

    /**
     * Set the signers of this class.
     */
    native void setSigners(Object[] signers);


//注意getXXX()表示,取得类中所有的(包括继承来的)public元素
//getDeclarDeclarXXX()表示取得类中所有的元素(不包括继承得来的,可以获得private的元素)
//如果想获得继承来的private元素,要取得父类的Class对象再调用getDeclarXXX()来获得
//无论怎样的get方法都是从getDeclaredXXX0()本地方法演变出来的
   
    /**
     *
     * 返回类中定义的declare类型的内部类或接口
     * 如果当前类对象表示数组,原始类型,void则直接返回null
     *
     */
    public native Class getDeclaringClass();


    /**
     *
     * 获得类的(包括继承)public的内部类或接口
     * 如果类没有公共的内部类或接口,或表示的是数组,或原始类型,或void则返回0长度的数组
     *
     */
    public Class[] getClasses() {
     //安全检查
        checkMemberAccess(Member.PUBLIC, ClassLoader.getCallerClassLoader());
       
    //调用doPrivileged方法时会调用PrivilegedAction接口的run方法
    //接口方法的实现体是在匿名内部类中定义的
 Class[] result = (Class[]) java.security.AccessController.doPrivileged
     (new java.security.PrivilegedAction() {
         public Object run() {
      java.util.List list = new java.util.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中 
    list.add(members[i]);
       }
   }
   
   //查找父类
   currentClass = currentClass.getSuperclass();
      }
     
      //将List转成数组
      return list.toArray(new Class[0]);
  }
     });

        return result;
    }


    /**
     *
     * 获得全部的(包括继承)public属性,得到的数组是无序的
     *
     */
    public Field[] getFields() throws SecurityException {
        checkMemberAccess(Member.PUBLIC, ClassLoader.getCallerClassLoader());
       
        return copyFields(privateGetPublicFields(null));
    }


    /**
     *
     *
     * 获得类全部的(包括继承的)public方法
     *
     */
    public Method[] getMethods() throws SecurityException {
     //安全检查
        checkMemberAccess(Member.PUBLIC, ClassLoader.getCallerClassLoader());
       
        return copyMethods(privateGetPublicMethods());
    }


    /**
     *
     * 获取当前类的全部(包括继承)pullic的构造函数
     */
    public Constructor[] getConstructors() throws SecurityException {
        checkMemberAccess(Member.PUBLIC, ClassLoader.getCallerClassLoader());
       
        return copyConstructors(privateGetDeclaredConstructors(true));
    }


    /**
     * 从类的全部范围(类自身,接口,父类)中查找相应名称的public属性对象
     * 查找顺序为,自身,递归查找接口,递归查找父类
     */
    public Field getField(String name)
        throws NoSuchFieldException, SecurityException {
     
        checkMemberAccess(Member.PUBLIC, ClassLoader.getCallerClassLoader());
       
        //查找属性对象
        Field field = getField0(name);
       
        if (field == null) {
            //如果没有找到则抛出异常
         throw new NoSuchFieldException(name);
        }
       
        return field;
    }


    /**
     * 通过方法名,参数类表,从类的全部范围(类自身,接口,父类)中查找相应的public方法对象
     * 查找顺序为,自身,递归查找接口,递归查找父类
     */
    public Method getMethod(String name, Class[] parameterTypes)
        throws NoSuchMethodException, SecurityException {
        checkMemberAccess(Member.PUBLIC, ClassLoader.getCallerClassLoader());
       
        //通过方法名,和参数列表,找到相应的publi的方法对象
        Method method = getMethod0(name, parameterTypes);
       
        if (method == null) {
         //如果没有找到则抛出异常
            throw new NoSuchMethodException(getName() + "." + name + argumentTypesToString(parameterTypes));
        }
       
        return method;
    }


    /**
     * 通过参数类表,从类的全部范围(类自身,接口,父类)中查找相应的public构造函数对象
     * 查找顺序为,自身,递归查找接口,递归查找父类
     */
    public Constructor getConstructor(Class[] parameterTypes)
        throws NoSuchMethodException, SecurityException {
        checkMemberAccess(Member.PUBLIC, ClassLoader.getCallerClassLoader());
       
        return getConstructor0(parameterTypes, Member.PUBLIC);
    }


    /**
     * 查找类定义中(不包括继承)的全部内部类(接口)
     */
    public Class[] getDeclaredClasses() throws SecurityException {
     //做安全判断
        checkMemberAccess(Member.DECLARED, ClassLoader.getCallerClassLoader());
       
        //调用本地方法取得本类中定义的所有内部类和接口
        return getDeclaredClasses0();
    }


    /**
     * 查找类定义中(不包括继承)的全部属性
     */
    public Field[] getDeclaredFields() throws SecurityException {
        checkMemberAccess(Member.DECLARED, ClassLoader.getCallerClassLoader());
       
        //fasle表示取declared型的
        return copyFields(privateGetDeclaredFields(false));
    }


    /**
     * 查找类定义中(不包括继承)的全部方法
     */
    public Method[] getDeclaredMethods() throws SecurityException {
        checkMemberAccess(Member.DECLARED, ClassLoader.getCallerClassLoader());
       
        return copyMethods(privateGetDeclaredMethods(false));
    }


    /**
     * 查找类定义中(不包括继承)的全部构造函数
     */
    public Constructor[] getDeclaredConstructors() throws SecurityException {
        checkMemberAccess(Member.DECLARED, ClassLoader.getCallerClassLoader());
        return copyConstructors(privateGetDeclaredConstructors(false));
    }


    /**
     * 通过属性名,查找类定义中(不包括继承)的相应的属性
     */
    public Field getDeclaredField(String name)
        throws NoSuchFieldException, SecurityException {
        checkMemberAccess(Member.DECLARED, ClassLoader.getCallerClassLoader());
       
        //在本类定义中查找相应属性名的属性对象
        Field field = searchFields(privateGetDeclaredFields(false), name);
       
        if (field == null) {
         //没有找到则抛出异常
            throw new NoSuchFieldException(name);
        }
        return field;
    }


    /**
     * 通过方法名,和参数列表,查找类定义中(不包括继承)的相应的方法
     */
    public Method getDeclaredMethod(String name, Class[] parameterTypes)
        throws NoSuchMethodException, SecurityException {
        checkMemberAccess(Member.DECLARED, ClassLoader.getCallerClassLoader());
       
        //通过方法名和参数列表,在本类定义中查找相应方法对象
        Method method = searchMethods(privateGetDeclaredMethods(false), name, parameterTypes);
       
        if (method == null) {
         //没有找到则抛出异常
            throw new NoSuchMethodException(getName() + "." + name + argumentTypesToString(parameterTypes));
        }
        return method;
    }


    /**
     * 通过参数列表,查找类定义中(不包括继承)的相应的构造函数
     */
    public Constructor getDeclaredConstructor(Class[] parameterTypes)
        throws NoSuchMethodException, SecurityException {
        checkMemberAccess(Member.DECLARED, ClassLoader.getCallerClassLoader());
        return getConstructor0(parameterTypes, Member.DECLARED);
    }


   
   
   
    /**
     * 通过给定名字查找资源,如果没有查到返回null
     */
    public InputStream getResourceAsStream(String name) {
        name = resolveName(name);
       
        //获得调用对象的ClassLoader
        ClassLoader cl = getClassLoader0();
       
        if (cl==null) {
            //如果调用的对象是由bootstrap ClassLoader装载的则使用
         //SystemClassLoader来装载资源
            return ClassLoader.getSystemResourceAsStream(name);
        }
       
        //使用调用遮的ClassLoader来装载资源
        return cl.getResourceAsStream(name);
    }


    /**
     * 通过给定名字查找资源,如果没有查到返回null
     */
    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);
    }

 

    /** protection domain returned when the internal domain is null */
    private static java.security.ProtectionDomain allPermDomain;


    /**
     * Returns the <code>ProtectionDomain</code> of this class.  If there is a
     * security manager installed, this method first calls the security
     * manager's <code>checkPermission</code> method with a
     * <code>RuntimePermission("getProtectionDomain")</code> permission to
     * ensure it's ok to get the
     * <code>ProtectionDomain</code>.
     *
     * @return the ProtectionDomain of this class
     *
     * @throws SecurityException
     *        if a security manager exists and its
     *        <code>checkPermission</code> method doesn't allow
     *        getting the ProtectionDomain.
     *
     * @see java.security.ProtectionDomain
     * @see SecurityManager#checkPermission
     * @see java.lang.RuntimePermission
     * @since 1.2
     */
    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;
    }


    /**
     * Returns the ProtectionDomain of this class.
     */
    private native java.security.ProtectionDomain getProtectionDomain0();


    /**
     * Set the ProtectionDomain for this class. Called by
     * ClassLoader.defineClass.
     */
    native void setProtectionDomain0(java.security.ProtectionDomain pd);


    //获得原始类型的Class对象,定义为友员的,在原始类型的封装类中使用
    static native Class getPrimitiveClass(String name);


    /*
     * Check if client is allowed to access members.  If access is denied,
     * throw a SecurityException.
     *
     * Be very careful not to change the stack depth of this checkMemberAccess
     * call for security reasons reasons see
     * java.lang.SecurityManager.checkMemberAccess
     *
     * <p> Default policy: allow all clients access with normal Java access
     * control.
     */
    private void checkMemberAccess(int which, ClassLoader ccl) {
        SecurityManager s = System.getSecurityManager();
        if (s != null) {
            s.checkMemberAccess(this, which);
     ClassLoader cl = getClassLoader0();
            if ((ccl != null) && (ccl != cl) &&
                  ((cl == null) || !cl.isAncestor(ccl))) {
  String name = this.getName();
  int i = name.lastIndexOf('.');
  if (i != -1) {
      s.checkPackageAccess(name.substring(0, i));
  }
     }
 }
    }

    //如果name是以"/"开头则去掉它,如果不是则在name前面加上以"/"分隔的包路径
    private String resolveName(String name) {
        if (name == null) {
         //如果为null直接返回
            return name;
        }
       
        if (!name.startsWith("/")) {//不是以"/"开头
            //取得当前Class对象
         Class c = this;
         
            while (c.isArray()) {
                //如果当前Class对象代表数组,则取出元素的类型
             c = c.getComponentType();
            }
            //取得类名
            String baseName = c.getName();
            int index = baseName.lastIndexOf('.');
            if (index != -1) {//不是原始类型
             //在name前面加上以"/"分隔的包路径
                name = baseName.substring(0, index).replace('.', '/')
                    +"/"+name;
            }
        } else {
         //如果是以"/"开头去掉"/"
            name = name.substring(1);
        }
        return name;
    }

    /**
     * Reflection support.
     */

    // 是否做缓存的标志
    private static boolean useCaches = true;
   
    //虽然对象已经没有引用,被垃圾回收,但是SoftReference通过get方法将重新获得
    //对referent的引用,除非内存紧张,referent将彻底被垃圾回收
    //Softreference对象用来缓存一个类中定义的相应的元素
    //public表示本类中的公共元素(注意不包括从祖先继承的public元素),declared表示本类中的全部元素
    private volatile transient SoftReference declaredFields;
    private volatile transient SoftReference publicFields;
   
    private volatile transient SoftReference declaredMethods;
    private volatile transient SoftReference publicMethods;
   
    private volatile transient SoftReference declaredConstructors;
    private volatile transient SoftReference publicConstructors;
   
    private volatile transient SoftReference declaredPublicFields;
    private volatile transient SoftReference declaredPublicMethods;

    //取得本类中声明的属性,publicOnly为true表示返回本类中的public属性
    //publicOnly为false表示取得本类中的全部属性
    private Field[] privateGetDeclaredFields(boolean publicOnly) {
     //检查初始化
        checkInitted();
       
        Field[] res = null;
       
        if (useCaches) {
        //要求缓存,从SoftReference中读取相应的public或全部属性
            if (publicOnly) {//取得本类中public的属性
                if (declaredPublicFields != null) {
                    res = (Field[]) declaredPublicFields.get();
                }
            } else {//取得本类中全部的属性
                if (declaredFields != null) {
                    res = (Field[]) declaredFields.get();
                }
            }
           
            //如果从缓存中取到则直接返回
            if (res != null) return res;
        }
       
        // 通过本地方法获得本类中公共的或全部的属性
        res = getDeclaredFields0(publicOnly);
       
        if (useCaches) {
         //如果需要缓存,做缓存处理
            if (publicOnly) {
                declaredPublicFields = new SoftReference(res);
            } else {
                declaredFields = new SoftReference(res);
            }
        }
        return res;
    }

    //取得类中所有的(包括祖先的)public属性()
    //traversedInterfaces表示排除掉的接口集合
    private Field[] privateGetPublicFields(Set traversedInterfaces) {
     //检查初始化
        checkInitted();
       
        //表示属性的数组
        Field[] res = null;
       
        if (useCaches) {
         //从缓存中得到属性数组
            if (publicFields != null) {
                res = (Field[]) publicFields.get();
            }
           
            //如果缓存中存在属性数组则直接返回
            if (res != null) return res;
        }

        List fields = new ArrayList();
       
        if (traversedInterfaces == null) {
            traversedInterfaces = new HashSet();
        }
       
        //获得本类的公共属性
        Field[] tmp = privateGetDeclaredFields(true);
        //将属性数组中的元素存放到List中
        addAll(fields, tmp);

        // Direct superinterfaces, recursively
        //获得此类的接口数组
        Class[] interfaces = getInterfaces();
       
       
        for (int i = 0; i < interfaces.length; i++) {
         //迭代类的所有接口
            Class c = interfaces[i];
            if (!traversedInterfaces.contains(c)) {//此接口没有被排除掉,或没有处理过
             //处理过的接口将被加入traversedInterfaces中
                traversedInterfaces.add(c);
                //递归调用,取得接口中的公共属性,并加入到List中
                addAll(fields, c.privateGetPublicFields(traversedInterfaces));
            }
        }
       

        //如果当前类对象不是接口则将父类中的属性加入到List中
        if (!isInterface()) {
         //获得父类Class对象
            Class c = getSuperclass();
           
            if (c != null) {
             //递归调用,取得父类中的公共属性,并将属性加入到List中
                addAll(fields, c.privateGetPublicFields(traversedInterfaces));
            }
        }

        //将属性元素封装到数组中
        res = new Field[fields.size()];
        fields.toArray(res);
       
        if (useCaches) {
         //如果需要缓存则做缓存处理
            publicFields = new SoftReference(res);
        }
       
        return res;
    }

    //将数组中元素存放到集合中
    private static void addAll(Collection c, Field[] o) {
        for (int i = 0; i < o.length; i++) {
            c.add(o[i]);
        }
    }


    //取得本类中声明的构造函数,publicOnly为true表示返回本类中的public构造函数
    //publicOnly为false表示取得本类中的全部构造函数
    private Constructor[] privateGetDeclaredConstructors(boolean publicOnly) {
     //检查初始化
        checkInitted();
        Constructor[] res = null;
       
        if (useCaches) {
         //使用缓存,这个是通过System.getProperty("sun.reflect.noCaches")来获得
            if (publicOnly) {//public型
                if (publicConstructors != null) {
                 //从reference对象中获得public型构造函数数组
                    res = (Constructor[]) publicConstructors.get();
                }
            } else {//declare型
                if (declaredConstructors != null) {
                 //从reference对象中获得declare型构造函数数组
                    res = (Constructor[]) declaredConstructors.get();
                }
            }
           
            //如果从缓存中取到构造函数数组则直接返回
            if (res != null) return res;
        }
       
        // 不做缓存,或没有取到构造函数数组
        if (isInterface()) {
         //如果是接口生成空的构造函数数组
            res = new Constructor[0];
        } else {//是类
         //取得构造函数数组,是一个本地方法
            res = getDeclaredConstructors0(publicOnly);
        }
       
        if (useCaches) {//如果使用缓存,则对其进行缓存
            if (publicOnly) {
                publicConstructors = new SoftReference(res);
            } else {
                declaredConstructors = new SoftReference(res);
            }
        }
       
        return res;
    }

    //获得本类中的public或全部的(declare)的方法,注意不包括祖先中定义的
    //publicOnly为true表示取public,为false表示取declare的
    private Method[] privateGetDeclaredMethods(boolean publicOnly) {
     //判断是否初始化
        checkInitted();
       
        Method[] res = null;
       
        if (useCaches) {
         //有缓存,则从SoftReference中取得public或declare的方法数组
            if (publicOnly) {
                if (declaredPublicMethods != null) {
                    res = (Method[]) declaredPublicMethods.get();
                }
            } else {
                if (declaredMethods != null) {
                    res = (Method[]) declaredMethods.get();
                }
            }
           
            //从缓存中取到直接返回
            if (res != null) return res;
        }
       
        //调用本地方法,取得本类中public或declare的方法
        res = getDeclaredMethods0(publicOnly);
       
        if (useCaches) {//如果进行缓存,则缓存方法数组
            if (publicOnly) {
                declaredPublicMethods = new SoftReference(res);
            } else {
                declaredMethods = new SoftReference(res);
            }
        }
       
        return res;
    }

    //一个静态内部类,含有一个方法数组
    static class MethodArray {
     //方法数组
        private Method[] methods;
        //表示此数组中有多少个方法对象
        private int length;

        //构造函数
        MethodArray() {
         //初始化数组长度20,没有元素
            methods = new Method[20];
            length = 0;
        }
       
        //增加方法对象
        void add(Method m) {
         //如果所含元素个数与数组最大长度相同,则扩充数组长度,扩充为原来的2倍
            if (length == methods.length) {
             //生成新的2倍长度的数组
                Method[] newMethods = new Method[2 * methods.length];
                //将原数据拷贝到新数组中
                System.arraycopy(methods, 0, newMethods, 0, methods.length);
                methods = newMethods;
            }
           
            //将要添加的的方法对象添加到数组中
            methods[length++] = m;
        }

        //添加一个方法数组中的全部元素
        void addAll(Method[] ma) {
            for (int i = 0; i < ma.length; i++) {
             //这里没有做null的判断,null也将加入
                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);
        }

        //将MethodArray对象中的没有在当前数组中存在的元素添加到当前数组
        void addAllIfNotPresent(MethodArray newMethods) {
            for (int i = 0; i < newMethods.length(); i++) {
                Method m = newMethods.get(i);
                if (m != null) {
                    addIfNotPresent(m);
                }
            }
        }

        //返回元素个数
        int length() {
            return length;
        }

        //返回制定位置的方法元素
        Method get(int i) {
            return methods[i];
        }

        //如果当前数组中有制定方法对象将数组的相应位置设为null
        void removeByNameAndSignature(Method toRemove) {
            for (int i = 0; i < length; i++) {//轮循方法数组
                Method m = methods[i];
               
                //方法相等的条件是,返回值相等,方法名相等,参数类表相等
                if (m != null &&
                    m.getReturnType() == toRemove.getReturnType() &&
                    m.getName() == toRemove.getName() &&
                    arrayContentsEq(m.getParameterTypes(),
                                    toRemove.getParameterTypes())) {                 
                 //如果含有此元素则置为null
                    methods[i] = null;
                }
            }
        }

        void compactAndTrim() {
         //连续元素的最后+1位置
            int newPos = 0;
            // 去掉null元素,如果出现null则只pos加一,如果出现移动则newPos加1
            for (int pos = 0; pos < length; pos++) {
                //轮循取出数组中的每个元素
             Method m = methods[pos];
               
                if (m != null) {
                 //如果当前元素不为null且当前位置与将要移动的位置不等
                 //则将元素拷贝到newPos位置上,随后newPos加1
                    if (pos != newPos) {
                        methods[newPos] = m;
                    }
                    newPos++;
                }
            }
           
            if (newPos != methods.length) {
             //如果有null元素,则缩短数组长度,使其饱满
             //按新长度(比原来小)生成新的方法数组
                Method[] newMethods = new Method[newPos];
                //拷贝数组
                System.arraycopy(methods, 0, newMethods, 0, newPos);
                //将生成数组付给当前类的数组变量
                methods = newMethods;
            }
        }

        //返回数组
        Method[] getArray() {
            return methods;
        }
    }


    // Returns an array of "root" methods. These Method objects must NOT
    // be propagated to the outside world, but must instead be copied
    // via ReflectionFactory.copyMethod.
    private Method[] privateGetPublicMethods() {
     //检查是否初始化
        checkInitted();
        Method[] res = null;
        if (useCaches) {//缓存
            if (publicMethods != null) {
             //从SoftReference中取得方法数组
                res = (Method[]) publicMethods.get();
            }
            if (res != null) return res;
        }

        //生成一个存储和操作一组方法的对象
        MethodArray methods = new MethodArray();
       
        //使用了一个块
        {
         //获取本类中的公共方法
            Method[] tmp = privateGetDeclaredMethods(true);
            //将方法数组封装到MethodArray类中
            methods.addAll(tmp);
        }
       
        // Now recur over superclass and direct superinterfaces.
        // Go over superinterfaces first so we can more easily filter
        // out concrete implementations inherited from superclasses at
        // the end.
       
        //inheritedMethods中存放继承的来的public方法
        MethodArray inheritedMethods = new MethodArray();
        //取得当前类的接口数组
        Class[] interfaces = getInterfaces();
       
        //迭代数组,分别取得每个接口中的公共方法,并将其加入到inheritedMethods中
        for (int i = 0; i < interfaces.length; i++) {
            inheritedMethods.addAll(interfaces[i].privateGetPublicMethods());
        }
       
        if (!isInterface()) {
         //如果当前类不是接口,则取得父类
            Class c = getSuperclass();
           
            if (c != null) {//父类不为null,表示当前类为Ojbect,或原始类型,或void
                //存放父类中的公共方法
             MethodArray supers = new MethodArray();               
             //将父类的公共方法添加到supers中
                supers.addAll(c.privateGetPublicMethods());
               
                for (int i = 0; i < supers.length(); i++) {
                    Method m = supers.get(i);
                    if (m != null && !Modifier.isAbstract(m.getModifiers())) {
                     //清楚从接口中继承的和类中继承的重复的方法
                        inheritedMethods.removeByNameAndSignature(m);
                    }
                }
               
                //将父类中继承的方法与接口中继承的方法整合
                supers.addAll(inheritedMethods);
                inheritedMethods = supers;
            }
        }
       
        //清除当前类中定义的方法与继承的来的方法相重复的方法
        for (int i = 0; i < methods.length(); i++) {
            Method m = methods.get(i);
            inheritedMethods.removeByNameAndSignature(m);
        }
       
        //将继承来分方法与类中定义的方法整合
        //注意方法在数组中存放的顺序,先是类中定义的方法,
        //然后是父类中定义的方法,最后是接口中定义的方法
        methods.addAllIfNotPresent(inheritedMethods);
        //清空null并缩短数组长度
        methods.compactAndTrim();
        //取得对象中封装的方法数组
        res = methods.getArray();
        if (useCaches) {//如果要求缓存,则进行缓存
            publicMethods = new SoftReference(res);
        }
       
        return res;
    }


    //从Field数组中取得属性名为name的属性对象
    private Field searchFields(Field[] fields, String name) {
     //表示将name池化
        String internedName = name.intern();
       
        for (int i = 0; i < fields.length; i++) {
            if (fields[i].getName() == internedName) {
                //返回与字段名相等的Field字段
             return getReflectionFactory().copyField(fields[i]);
            }
        }
       
        //找不到返回null
        return null;
    }

    //从类的全部范围(类自身,接口,父类)中查找相应名称的public属性对象
    //查找顺序为,自身,递归查找接口,递归查找父类
    private Field getField0(String name) throws NoSuchFieldException {
        Field res = null;
        // Search declared public fields
       
        //得到本类中定义的public的属性数组
        //如果在本类中定义的public属性中能找到此名称的属性对象则返回
        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;
                }
            }
        }
       
        //如果找不到返回null
        return null;
    }

    //从方法数组中查找相应的方法对象
    private static Method searchMethods(Method[] methods,
                                        String name,
                                        Class[] parameterTypes)
    {    
  Method res = null;
   //我认为m.getName()得到的是字符串常量,这个是由native方法生成的
      //而internedName是通过name.intern()得到,这样可以与
      //m.getName()直接做==比较
        String internedName = name.intern();
       
        //迭代方法数组取得相应的方法对象
        for (int i = 0; i < methods.length; i++) {
         
     Method m = methods[i];
    
     //方法对象匹配的要求是,方法名相同,参数类表相同,方法的返回值
     //与取得分方法对象的返回值的一致,或是它的父类
            if (m.getName() == internedName             
  && arrayContentsEq(parameterTypes, m.getParameterTypes())
  && (res == null
      || res.getReturnType().isAssignableFrom(m.getReturnType())))
             
        //取得此方法对象     
  res = m;
        }

 return (res == null ? res : getReflectionFactory().copyMethod(res));
    }
 
    //从类的全部范围(类自身,接口,父类)中查找相应名称的public方法对象
    //查找顺序为,自身,递归查找接口,递归查找父类
    private Method getMethod0(String name, Class[] parameterTypes) {
        Method res = null;
       
        //从当前类中查找对应的方法对象
        if ((res = searchMethods(privateGetDeclaredMethods(true),
                                 name,
                                 parameterTypes)) != null) {
            return res;
        }
       
        //如果没有找到,则递归查找接口
        if (!isInterface()) {
            Class c = getSuperclass();
            if (c != null) {
                if ((res = c.getMethod0(name, parameterTypes)) != null) {
                    return res;
                }
            }
        }
       
        //如果没有找到,则递归查找父类
        Class[] interfaces = getInterfaces();
        for (int i = 0; i < interfaces.length; i++) {
            Class c = interfaces[i];
            if ((res = c.getMethod0(name, parameterTypes)) != null) {
                return res;
            }
        }
       
        //没有找到返回null
        return null;
    }

    //取得相应参数列表和描述(public,declared)的构造函数
    private Constructor getConstructor0(Class[] parameterTypes,
                                        int which) throws NoSuchMethodException
    {
     //which == Member.PUBLIC为false
        Constructor[] constructors = privateGetDeclaredConstructors((which == Member.PUBLIC));
       
        for (int i = 0; i < constructors.length; i++) {
         //找到参数列表相同的构造函数
            if (arrayContentsEq(parameterTypes,
                                constructors[i].getParameterTypes())) {
             
             //返回得到的构造函数
                return getReflectionFactory().copyConstructor(constructors[i]);
            }
        }
       
        //如果没有找到相应参数的构造函数抛出异常
        throw new NoSuchMethodException(getName() + ".<init>" + argumentTypesToString(parameterTypes));
    }

    //比较两个数组是否相等
    private static boolean arrayContentsEq(Object[] a1, Object[] a2) {
        if (a1 == null) {
         //如果a1为null则a2为null或a2的长度为0返回true,否则返回false
            return a2 == null || a2.length == 0;
        }

        if (a2 == null) {
         //a2为nulla1不为null则a1长度为0返回true
            return a1.length == 0;
        }

        //两个数组长度不等返回false
        if (a1.length != a2.length) {
            return false;
        }

        //比较两数组中的各个元素
        for (int i = 0; i < a1.length; i++) {
            if (a1[i] != a2[i]) {
                return false;
            }
        }

        return true;
    }

    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 Constructor[] copyConstructors(Constructor[] arg) {
        Constructor[] out = new Constructor[arg.length];
        ReflectionFactory fact = getReflectionFactory();
        for (int i = 0; i < arg.length; i++) {
            out[i] = fact.copyConstructor(arg[i]);
        }
        return out;
    }

    //取得类中不同元素的元素
    //publicOnly为true表示取得public型的元素,false表示取得declared型的元素
    //都是指本类中定义的元素,不包括父类中定义的元素
    private native Field[]       getDeclaredFields0(boolean publicOnly);
    private native Method[]      getDeclaredMethods0(boolean publicOnly);
    private native Constructor[] getDeclaredConstructors0(boolean publicOnly);
    //表明在类中声明的内部类
    private native Class[]       getDeclaredClasses0();

    private static String        argumentTypesToString(Class[] argTypes) {
        StringBuffer buf = new StringBuffer();
        buf.append("(");
        if (argTypes != null) {
            for (int i = 0; i < argTypes.length; i++) {
                if (i > 0) {
                    buf.append(", ");
                }
  Class c = argTypes[i];
  buf.append((c == null) ? "null" : c.getName());
            }
        }
        buf.append(")");
        return buf.toString();
    }

    /** use serialVersionUID from JDK 1.1 for interoperability */
    private static final long serialVersionUID = 3206093459760846163L;


    /**
     * Class Class is special cased within the Serialization Stream Protocol.
     *
     * A Class instance is written intially into an ObjectOutputStream in the
     * following format:
     * <pre>
     *      <code>TC_CLASS</code> ClassDescriptor
     *      A ClassDescriptor is a special cased serialization of
     *      a <code>java.io.ObjectStreamClass</code> instance.
     * </pre>
     * A new handle is generated for the initial time the class descriptor
     * is written into the stream. Future references to the class descriptor
     * are written as references to the initial class descriptor instance.
     *
     * @see java.io.ObjectStreamClass
     */
    private static final ObjectStreamField[] serialPersistentFields =
        ObjectStreamClass.NO_FIELDS;


    /**
     * Returns the assertion status that would be assigned to this
     * class if it were to be initialized at the time this method is invoked.
     * If this class has had its assertion status set, the most recent
     * setting will be returned; otherwise, if any package default assertion
     * status pertains to this class, the most recent setting for the most
     * specific pertinent package default assertion status is returned;
     * otherwise, if this class is not a system class (i.e., it has a
     * class loader) its class loader's default assertion status is returned;
     * otherwise, the system class default assertion status is returned.
     * <p>
     * Few programmers will have any need for this method; it is provided
     * for the benefit of the JRE itself.  (It allows a class to determine at
     * the time that it is initialized whether assertions should be enabled.)
     * Note that this method is not guaranteed to return the actual
     * assertion status that was (or will be) associated with the specified
     * class when it was (or will be) initialized.
     *
     * @return the desired assertion status of the specified class.
     * @see    java.lang.ClassLoader#setClassAssertionStatus
     * @see    java.lang.ClassLoader#setPackageAssertionStatus
     * @see    java.lang.ClassLoader#setDefaultAssertionStatus
     * @since  1.4
     */
    public boolean desiredAssertionStatus() {
        ClassLoader loader = getClassLoader();
        // If the loader is null this is a system class, so ask the VM
        if (loader == null)
            return desiredAssertionStatus0(this);

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

    // Retrieves the desired assertion status of this class from the VM
    private static native boolean desiredAssertionStatus0(Class clazz);

    // Fetches the factory for reflective objects
    private static ReflectionFactory getReflectionFactory() {
        if (reflectionFactory == null) {
            reflectionFactory =  (ReflectionFactory)
                java.security.AccessController.doPrivileged
                    (new sun.reflect.ReflectionFactory.GetReflectionFactoryAction());
        }
        return reflectionFactory;
    }
   
    private static ReflectionFactory reflectionFactory;

    //判断是否System已经被初始化
    private static boolean initted = false;
   
    //检验初始化
    private static void checkInitted() {
     //如果已经初始化直接返回
        if (initted) return;
       
        AccessController.doPrivileged(new PrivilegedAction() {
                public Object run() {                   
                 //System.out不为null表明System类已经被初始化,且启动代码已经运行
                    if (System.out == null) {
                        // System类未被初始化返回null
                        return null;
                    }

                    //取得是不不用缓存的参数
                    String val =
                        System.getProperty("sun.reflect.noCaches");
                   
                    if (val != null && val.equals("true")) {
                        useCaches = false;
                    }
         
                    //标志初始完成
                    initted = true;
                    return null;
                }
            });
    }

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值