reflect包源码笔记


在这里插入图片描述

AnnotatedElement

@Since:1.5

Comment:表示当前在此VM中运行的程序的一个带注解的元素。这个接口允许反射地读取注解。该接口中方法返回的所有注解都是不可变和可序列化的。调用方可以修改此接口方法返回的数组,而不会影响返回给其他调用方的数组。

// @Since:1.5
// 如果此元素上存在指定类型的注释,则返回true,否则返回false。 该方法主要用于方便访问标记注释。 
default boolean isAnnotationPresent(Class<? extends Annotation> annotationClass) {
   
    return getAnnotation(annotationClass) != null;
}
// @Since:1.5
// 如果存在指定类型的注释,则返回该元素的注释,否则为空。
<T extends Annotation> T getAnnotation(Class<T> annotationClass);
// @Since:1.5
// 返回出现在此元素上的注释。
Annotation[] getAnnotations();
// @Since:1.8
// 返回与此元素关联的注释。
// 该方法与 getAnnotation(Class) 的区别在于,该方法检测其参数是否为可重复注释类型(JLS 9.6),如果是,则试图通过“查看”容器注释来查找该类型的一个或多个注释。
// @implSpec:默认实现首先调用 getDeclaredAnnotationsByType(Class) ,传递 annotationClass 作为参数。如果返回的数组长度大于0,则返回该数组。如果返回的数组是零长度的,并且这个 AnnotatedElement 是一个类,参数类型是一个可继承的注释类型,并且这个 AnnotatedElement 的超类是非空的,那么返回的结果就是在超类上以 annotationClass 为参数调用 getAnnotationsByType(class) 的结果。否则,返回一个零长度的数组。
default <T extends Annotation> T[] getAnnotationsByType(Class<T> annotationClass) {
   
    /* 关联的定义:直接或间接呈现或既不直接也不间接呈现且元素是Class,注释类型是可继承的,且注释类型与元素的超类关联。
    */
    T[] result = getDeclaredAnnotationsByType(annotationClass);

    if (result.length == 0 && // Neither directly nor indirectly present
        this instanceof Class && // the element is a class
        AnnotationType.getInstance(annotationClass).isInherited()) {
    // Inheritable
        Class<?> superClass = ((Class<?>) this).getSuperclass();
        if (superClass != null) {
   
            // Determine if the annotation is associated with the
            // superclass
            result = superClass.getAnnotationsByType(annotationClass);
        }
    }

    return result;
}
// @Since:1.8
// 如果指定类型的注释直接存在,则返回该元素的注释,否则为空。
default <T extends Annotation> T getDeclaredAnnotation(Class<T> annotationClass) {
   
    Objects.requireNonNull(annotationClass);
    // Loop over all directly-present annotations looking for a matching one
    for (Annotation annotation : getDeclaredAnnotations()) {
   
        if (annotationClass.equals(annotation.annotationType())) {
   
            // More robust to do a dynamic cast at runtime instead
            // of compile-time only.
            return annotationClass.cast(annotation);
        }
    }
    return null;
}
// @Since:1.8
// 如果指定类型的注释直接或间接地存在,则返回该元素的注释。此方法忽略继承的注释。
default <T extends Annotation> T[] getDeclaredAnnotationsByType(Class<T> annotationClass) {
   
    Objects.requireNonNull(annotationClass);
    return AnnotationSupport.
        getDirectlyAndIndirectlyPresent(Arrays.stream(getDeclaredAnnotations()).
                                        collect(Collectors.toMap(Annotation::annotationType,
                                                                 Function.identity(),
                                                                 ((first,second) -> first),
                                                                 LinkedHashMap::new)),
                                        annotationClass);
}
// @Since:1.5
// 返回直接出现在此元素上的注释。此方法忽略继承的注释。
Annotation[] getDeclaredAnnotations();

AnnotatedType

参考连接:Java反射之AnnotatedType接口
在这里插入图片描述

@Since:1.8

Comment:表示当前运行在该虚拟机中的程序中某个类型的潜在注释使用。可以使用Java编程语言中的任何类型,包括数组类型、参数化类型、类型变量或通配符类型。

// 返回此带注释的类型所表示的基础类型。
public Type getType();

AnnotatedArrayType

@Since:1.8

Comment:表示一个数组类型的潜在注释使用,其组件类型本身可能代表一个类型的注释使用。

// 返回此数组类型的可能带注释的泛型组件类型。
AnnotatedType  getAnnotatedGenericComponentType();

AnnotatedParameterizedType

@Since:1.8

Comment:表示参数化类型的潜在注释使用,其类型参数本身可以表示类型的注释使用。

// 返回此参数化类型的可能带注释的实际类型参数。
AnnotatedType[] getAnnotatedActualTypeArguments();

AnnotatedTypeVariable

@Since:1.8

Comment:表示类型变量的潜在注释使用,它的声明可能有边界,这些边界本身代表类型的注释使用。

// 返回此类型变量可能带注释的边界。
AnnotatedType[] getAnnotatedBounds();

AnnotatedWildcardType

@Since:1.8

Comment:表示通配符类型参数的潜在注释用法,通配符类型参数的上界或下界本身可以表示类型的注释用法。

// 返回此通配符类型可能带有注释的下界。
AnnotatedType[] getAnnotatedLowerBounds();
// 返回此通配符类型可能带有注释的上界。
AnnotatedType[] getAnnotatedUpperBounds();

测试代码:

@Retention(RetentionPolicy.RUNTIME)
@Target({
   ElementType.TYPE, ElementType.METHOD, ElementType.FIELD, ElementType.CONSTRUCTOR, ElementType.PARAMETER, ElementType.LOCAL_VARIABLE, ElementType.TYPE_USE})
@Inherited
@interface MyAnno {
   
    String value() default "";
}

class MyAnnoClass<@MyAnno T extends @MyAnno Number, U> {
   
    @MyAnno T[] tArr;
    T t;
    List<@MyAnno ? extends Number> list;

}

public static void main(String[] args) {
   
    Field[] annotatedInterfaces = MyAnnoClass.class.getDeclaredFields();
    System.out.printf("|%20s|%50s|%80s|%20s|%20s|%20s|%30s|%20s|%n",
            "Field Name", "annotatedType Name", "annotatedTypeClass Name", "modifier",
            "AnnotatedArrayType", "AnnotatedTypeVariable", "AnnotatedParameterizedType", "AnnotatedWildcardType");
    for (Field field : annotatedInterfaces) {
   
        AnnotatedType annotatedType = field.getAnnotatedType();
        // AnnotatedArrayType: 1000, AnnotatedTypeVariable: 0100, AnnotatedParameterizedType: 0010, AnnotatedWildcardType: 0001
        int modifier = 0;
        String arrayTypeInfo = "";
        String typeVariableInfo = "";
        String parameterizedTypeInfo = "";
        String wildcardTypeInfo = "";
        if (annotatedType instanceof AnnotatedArrayType) {
   
            modifier |= 0b1000;
            arrayTypeInfo = ((AnnotatedArrayType) annotatedType).getAnnotatedGenericComponentType().getType().getTypeName();
        }
        if (annotatedType instanceof AnnotatedTypeVariable) {
   
            modifier |= 0b0100;
            typeVariableInfo = Arrays.toString(Arrays.stream(((AnnotatedTypeVariable) annotatedType).getAnnotatedBounds()).map(annoType -> annoType.getType().getTypeName()).toArray());
        }
        if (annotatedType instanceof AnnotatedParameterizedType) {
   
            modifier |= 0b0010;
            parameterizedTypeInfo = Arrays.toString(Arrays.stream(((AnnotatedParameterizedType) annotatedType).getAnnotatedActualTypeArguments()).map(annoType -> annoType.getType().getTypeName()).toArray());
            for (AnnotatedType annotatedActualTypeArgument : ((AnnotatedParameterizedType) annotatedType).getAnnotatedActualTypeArguments()) {
   
                if (annotatedActualTypeArgument instanceof AnnotatedWildcardType) {
   
                    modifier |= 0b0001;
                    wildcardTypeInfo = Arrays.toString(Arrays.stream(((AnnotatedWildcardType) annotatedActualTypeArgument).getAnnotatedUpperBounds()).map(annoType -> annoType.getType().getTypeName()).toArray());
                }
            }
        }
        System.out.printf("|%20s|%50s|%80s|%20s|%20s|%20s|%30s|%20s|%n",
                field.getName(), annotatedType.getType().getTypeName(), annotatedType.getClass().getName(),
                String.format("%1$04d", Integer.valueOf(Integer.toBinaryString(modifier))),
                arrayTypeInfo, typeVariableInfo, parameterizedTypeInfo, wildcardTypeInfo);
    }
}

测试结果:

|          Field Name|                                annotatedType Name|                                                         annotatedTypeClass Name|            modifier|  AnnotatedArrayType|AnnotatedTypeVariable|    AnnotatedParameterizedType|AnnotatedWildcardType|
|                tArr|                                               T[]|              sun.reflect.annotation.AnnotatedTypeFactory$AnnotatedArrayTypeImpl|                1000|                   T|                    |                              |                    |
|                   t|                                                 T|           sun.reflect.annotation.AnnotatedTypeFactory$AnnotatedTypeVariableImpl|                0100|                    |  [java.lang.Number]|                              |                    |
|                list|        java.util.List<? extends java.lang.Number>|      sun.reflect.annotation.AnnotatedTypeFactory$AnnotatedParameterizedTypeImpl|                0011|                    |                    |  [? extends java.lang.Number]|  [java.lang.Number]|

Member

Comment:Member是一个接口,它反映关于单个成员(字段或方法)或构造函数的标识信息。

// 标识类或接口的所有公共成员的集合,包括继承的成员。
public static final int PUBLIC = 0;
// 标识类或接口声明的成员集。不包括继承的成员。
public static final int DECLARED = 1;
// 返回表示声明由该成员表示的成员或构造函数的类或接口的Class对象。
public Class<?> getDeclaringClass();
// 返回由该成员表示的基础成员或构造函数的简单名称。
public String getName();
// 以整数形式返回此成员表示的成员或构造函数的Java语言修饰符。应该使用Modifier类来解码整数中的修饰符。
public int getModifiers();
// @Since:1.5
// 如果该成员是由编译器引入的,则返回 true ;否则返回 false 。
public boolean isSynthetic();

Modifier

Comment:Modifier类提供了static方法和常量来解码类和成员访问修饰符。 修饰符集合被表示为具有表示不同修饰符的不同位位置的整数。 表示修饰符的常量的值取自The Java™ Virtual Machine Specification的第4.1,4.4,4.5和4.7节中的表

// java.Lang和java.lang.reflect包之间的引导协议。
static {
   
    sun.reflect.ReflectionFactory factory =
        AccessController.doPrivileged(
            new ReflectionFactory.GetReflectionFactoryAction());
    factory.setLangReflectAccess(new java.lang.reflect.ReflectAccess());
}
public static final int PUBLIC           = 0x00000001;
public static final int PRIVATE          = 0x00000002;
public static final int PROTECTED        = 0x00000004;
public static final int STATIC           = 0x00000008;
public static final int FINAL            = 0x00000010;
public static final int SYNCHRONIZED     = 0x00000020;
public static final int VOLATILE         = 0x00000040;
public static final int TRANSIENT        = 0x00000080;
public static final int NATIVE           = 0x00000100;
public static final int INTERFACE        = 0x00000200;
public static final int ABSTRACT         = 0x00000400;
public static final int STRICT           = 0x00000800;
// 没有(还)公开在公共API中的位,要么是因为它们对字段和方法有不同的含义,在这个类中没有办法区分这两者,要么是因为它们不是Java编程语言的关键字
static final int BRIDGE    = 0x00000040;
static final int VARARGS   = 0x00000080;
static final int SYNTHETIC = 0x00001000;
static final int ANNOTATION  = 0x00002000;
static final int ENUM      = 0x00004000;
static final int MANDATED  = 0x00008000;
public static boolean isPublic(int mod) {
    return (mod & PUBLIC) != 0; }
public static boolean isPrivate(int mod) {
    return (mod & PRIVATE) != 0; }
public static boolean isProtected(int mod) {
    return (mod & PROTECTED) != 0; }
public static boolean isStatic(int mod) {
    return (mod & STATIC) != 0; }
public static boolean isFinal(int mod) {
    return (mod & FINAL) != 0; }
public static boolean isSynchronized(int mod) {
    return (mod & SYNCHRONIZED) != 0; }
public static boolean isVolatile(int mod) {
    return (mod & VOLATILE) != 0; }
public static boolean isTransient(int mod) {
    return (mod & TRANSIENT) != 0; }
public static boolean isNative(int mod) {
    return (mod & NATIVE) != 0; }
public static boolean isInterface(int mod) {
    return (mod & INTERFACE) != 0; }
public static boolean isAbstract(int mod) {
    return (mod & ABSTRACT) != 0; }
public static boolean isStrict(int mod) {
    return (mod & STRICT) != 0; }
static boolean isSynthetic(int mod) {
    return (mod & SYNTHETIC) != 0; }
static boolean isMandated(int mod) {
    return (mod & MANDATED) != 0; }
// 返回一个字符串,描述指定修饰符中的访问修饰符标志。
public static String toString(int mod) {
   
    StringBuilder sb = new StringBuilder();
    int len;

    if ((mod & PUBLIC) != 0)        sb.append("public ");
    if ((mod & PROTECTED) != 0)     sb.append("protected ");
    if ((mod & PRIVATE) != 0)       sb.append("private ");

    /* Canonical order */
    if ((mod & ABSTRACT) != 0)      sb.append("abstract ");
    if ((mod & STATIC) != 0)        sb.append("static ");
    if ((mod & FINAL) != 0)         sb.append("final ");
    if ((mod & TRANSIENT) != 0)     sb.append("transient ");
    if ((mod & VOLATILE) != 0)      sb.append("volatile ");
    if ((mod & SYNCHRONIZED) != 0)  sb.append("synchronized ");
    if ((mod & NATIVE) != 0)        sb.append("native ");
    if ((mod & STRICT) != 0)        sb.append("strictfp ");
    if ((mod & INTERFACE) != 0)     sb.append("interface ");

    if ((len = sb.length()) > 0)    /* trim trailing space */
        return sb.toString().substring(0, len-1);
    return "";
}
private static final int CLASS_MODIFIERS =
        Modifier.PUBLIC         | Modifier.PROTECTED    | Modifier.PRIVATE |
        Modifier.ABSTRACT       | Modifier.STATIC       | Modifier.FINAL   |
        Modifier.STRICT;
private static final int INTERFACE_MODIFIERS =
        Modifier.PUBLIC         | Modifier.PROTECTED    | Modifier.PRIVATE |
        Modifier.ABSTRACT       | Modifier.STATIC       | Modifier.STRICT;
private static final int CONSTRUCTOR_MODIFIERS =
        Modifier.PUBLIC         | Modifier.PROTECTED    | Modifier.PRIVATE;
private static final int METHOD_MODIFIERS =
        Modifier.PUBLIC         | Modifier.PROTECTED    | Modifier.PRIVATE |
        Modifier.ABSTRACT       | Modifier.STATIC       | Modifier.FINAL   |
        Modifier.SYNCHRONIZED   | Modifier.NATIVE       | Modifier.STRICT;
private static final int FIELD_MODIFIERS =
        Modifier.PUBLIC         | Modifier.PROTECTED    | Modifier.PRIVATE |
        Modifier.STATIC         | Modifier.FINAL        | Modifier.TRANSIENT |
        Modifier.VOLATILE;
private static final int PARAMETER_MODIFIERS =
        Modifier.FINAL;
static final int ACCESS_MODIFIERS =
        Modifier.PUBLIC | Modifier.PROTECTED | Modifier.PRIVATE;

public static int classModifiers() {
    return CLASS_MODIFIERS; }
public static int interfaceModifiers() {
    return INTERFACE_MODIFIERS; }
public static int constructorModifiers() {
    return CONSTRUCTOR_MODIFIERS; }
public static int methodModifiers() {
    return METHOD_MODIFIERS; }
public static int fieldModifiers() {
    return FIELD_MODIFIERS; }
public static int parameterModifiers() {
    return PARAMETER_MODIFIERS; }

ReflectAccess

Comment:实现sun.reflect.LangReflectAccess接口的包私有类,允许java.Lang包来实例化该包中的对象。

public Field newField(Class<?> declaringClass,
                      String name,
                      Class<?> type,
                      int modifiers,
                      int slot,
                      String signature,
                      byte[] annotations) {
   
    return new Field(declaringClass,
                     name,
                     type,
                     modifiers,
                     slot,
                     signature,
                     annotations);
}
public Method newMethod(Class<?> declaringClass,
                        String name,
                        Class<?>[] parameterTypes,
                        Class<?> returnType,
                        Class<?>[] checkedExceptions,
                        int modifiers,
                        int slot,
                        String signature,
                        byte[] annotations,
                        byte[] parameterAnnotations,
                        byte[] annotationDefault) {
   
    return new Method(declaringClass,
                      name,
                      parameterTypes,
                      returnType,
                      checkedExceptions,
                      modifiers,
                      slot,
                      signature,
                      annotations,
                      parameterAnnotations,
                      annotationDefault);
}
public <T> Constructor<T> newConstructor(Class<T> declaringClass,
                                         Class<?>[] parameterTypes,
                                         Class<?>[] checkedExceptions,
                                         int modifiers,
                                         int slot,
                                         String signature,
                                         byte[] annotations,
                                         byte[] parameterAnnotations) {
   
    return new Constructor<>(declaringClass,
                              parameterTypes,
                              checkedExceptions,
                              modifiers,
                              slot,
                              signature,
                              annotations,
                              parameterAnnotations);
}
public MethodAccessor getMethodAccessor(Method m) {
   
    return m.getMethodAccessor();
}
public void setMethodAccessor(Method m, MethodAccessor accessor) {
   
    m.setMethodAccessor(accessor);
}
public ConstructorAccessor getConstructorAccessor(Constructor<?> c) {
   
    return c.getConstructorAccessor();
}
public void setConstructorAccessor(Constructor<?> c,
                                   ConstructorAccessor accessor) {
   
    c.setConstructorAccessor(accessor);
}
public int getConstructorSlot(Constructor<?> c) {
   
    return c.getSlot();
}
public String getConstructorSignature(Constructor<?> c) {
   
    return c.getSignature();
}
public byte[] getConstructorAnnotations(Constructor<?> c) {
   
    return c.getRawAnnotations();
}
public byte[] getConstructorParameterAnnotations(Constructor<?> c) {
   
    return c.getRawParameterAnnotations();
}
public byte[] getExecutableTypeAnnotationBytes(Executable ex) {
   
    return ex.getTypeAnnotationBytes();
}
// 复制例程,需要从模板快速生成新的Field、Method和Constructor对象
public Method      copyMethod(Method arg) {
   
    return arg.copy();
}
public Field       copyField(Field arg) {
   
    return arg.copy();
}
public <T> Constructor<T> copyConstructor(Constructor<T> arg) {
   
    return arg.copy();
}

AccessibleObject

@Since:1.2

Comment:AccessibleObject类是Field、Method和Constructor对象的基类。它提供了在使用反射对象时将其标记为抑制默认Java语言访问控制检查的能力。当使用Field、Method和Constructor分别设置或获取字段、调用方法或创建和初始化类的新实例时,将执行访问检查——公共、默认(包)访问、受保护和私有成员。默认情况下,反射对象是不可访问的。

protected AccessibleObject() {
   }
// 指示该对象是否覆盖语言级访问检查。初始化“false”。该字段由field、Method和Constructor使用。
boolean override;
static final private java.security.Permission ACCESS_PERMISSION = new ReflectPermission("suppressAccessChecks");
static final ReflectionFactory reflectionFactory = AccessController.doPrivileged( new sun.reflect.ReflectionFactory.GetReflectionFactoryAction());
volatile Object securityCheckCache;
// 为一个对象数组设置{@code accessible}标志的方便方法,只需进行一次安全检查(为了效率)。
public static void setAccessible(AccessibleObject[] array, boolean flag)
    throws SecurityException {
   
    SecurityManager sm = System.getSecurityManager();
    if (sm != null) sm.checkPermission(ACCESS_PERMISSION);
    for (int i = 0; i < array.length; i++) {
   
        setAccessible0(array[i], flag);
    }
}
// 设置该对象的{@code accessible}标志为指定的布尔值。{@code true}的值表示反射对象在使用时应该禁止Java语言访问检查。{@code false}的值表示反射对象应该强制Java语言访问检查。
public void setAccessible(boolean flag) throws SecurityException {
   
    SecurityManager sm = System.getSecurityManager();
    if (sm != null) sm.checkPermission(ACCESS_PERMISSION);
    setAccessible0(this, flag);
}
// 检查你没有暴露java.lang.Class.<init>或java.lang.Class中的敏感字段。
private static void setAccessible0(AccessibleObject obj, boolean flag) throws SecurityException {
   
    if (obj instanceof Constructor && flag == true) {
   
        Constructor<?> c = (Constructor<?>)obj;
        if (c.getDeclaringClass() == Class.class) {
   
            throw new SecurityException("Cannot make a java.lang.Class" +
                                        " constructor accessible");
        }
    }
    obj.override = flag;
}
// 获取该对象的{@code accessible}标志的值。
public boolean isAccessible() {
   
    return override;
}
@Override
public <T extends Annotation> T getAnnotation(Class<T> annotationClass) {
   
    throw new AssertionError("All subclasses should override this method");
}
@Override
public boolean isAnnotationPresent(Class<? extends Annotation> annotationClass) {
   
    return AnnotatedElement.super.isAnnotationPresent(annotationClass);
}
@Override
public <T extends Annotation> T[] getAnnotationsByType(Class<T> annotationClass) {
   
    throw new AssertionError("All subclasses should override this method");
}
@Override
public Annotation[] getAnnotations() {
   
    return getDeclaredAnnotations();
}
@Override
public <T extends Annotation> T getDeclaredAnnotation(Class<T> annotationClass) {
   
    // 只有类上的注释被继承,对于所有其他对象,getDeclaredAnnotation与getAnnotation相同。
    return getAnnotation(annotationClass);
}
@Override
public <T extends Annotation> T[] getDeclaredAnnotationsByType(Class<T> annotationClass) {
   
    // 只有类上的注释被继承,对于所有其他对象getDeclaredAnnotationsByType与getAnnotationsByType相同。
    return getAnnotationsByType(annotationClass);
}
@Override
public Annotation[] getDeclaredAnnotations()  {
   
    throw new AssertionError("All subclasses should override this method");
}
void checkAccess(Class<?> caller, Class<?> clazz, Object obj, int modifiers) throws IllegalAccessException {
   
    if (caller == clazz) {
     // quick check
        return;             // ACCESS IS OK
    }
    Object cache = securityCheckCache;  // read volatile
    Class<?> targetClass = clazz;
    if (obj != null
        && Modifier.isProtected(modifiers)
        && ((targetClass = obj.getClass()) != clazz)) {
   
        // Must match a 2-list of { caller, targetClass }.
        if (cache instanceof Class[]) {
   
            Class<?>[] cache2 = (Class<?>[]) cache;
            if (cache2[1] == targetClass &&
                cache2[0] == caller) {
   
                return;     // ACCESS IS OK
            }
            // (Test cache[1] first since range check for [1]
            // subsumes range check for [0].)
        }
    } else if (cache == caller) {
   
        // Non-protected case (or obj.class == this.clazz).
        return;             // ACCESS IS OK
    }
    // If no return, fall through to the slow path.
    slowCheckMemberAccess(caller, clazz, obj, modifiers, targetClass);
}
// 把这些慢的东西都放一边:
void slowCheckMemberAccess(Class<?> caller, Class<?> clazz, Object obj, int modifiers, Class<?> targetClass) throws IllegalAccessException {
   
    Reflection.ensureMemberAccess(caller, clazz, obj, modifiers);
    // Success: Update the cache.
    Object cache = ((targetClass == clazz)
                    ? caller
                    : new Class<?>[] {
    caller, targetClass });

    // Note:  The two cache elements are not volatile,
    // but they are effectively final.  The Java memory model
    // guarantees that the initializing stores for the cache
    // elements will occur before the volatile write.
    securityCheckCache = cache;         // write volatile
}

Field

Comment:提供关于类或接口单个字段的信息和动态访问。反射的字段可以是一个类(静态)字段或一个实例字段。允许在get或set访问操作期间发生扩大转换,但如果将发生缩小转换,则会抛出 IllegalArgumentException 。

private Class<?>            clazz;
private int                 slot;
// 这可以保证在1.4反射实现中由VM实现
private String              name;
private Class<?>            type;
private int                 modifiers;
// 泛型和注释支持
private transient String    signature;
// 泛型信息存储库;延迟初始化
private transient FieldRepository genericInfo;
private byte[]              annotations;
// 不重写创建的缓存字段访问器
private FieldAccessor fieldAccessor;
// 用重写创建的缓存字段访问器
private FieldAccessor overrideFieldAccessor;
// 用于字段访问器的共享。这个分支结构目前只有两层深(也就是说,一个根Field和可能有很多Field对象指向它)。
// 如果这个分支结构包含循环,那么在注释代码中就可能发生死锁。
private Field               root;
private transient Map<Class<? extends Annotation>, Annotation> declaredAnnotations;
// 泛型基础设施
private String getGenericSignature() {
   return signature;}
// 返回{@code Class}对象,该对象表示声明由{@code field}对象表示的字段的类或接口。
public Class<?> getDeclaringClass() {
   
    return clazz;
}
// 访问器的工厂
private GenericsFactory getFactory() {
   
    Class<?> c = getDeclaringClass();
    // 创建范围和工厂
    return CoreReflectionFactory.make(c, ClassScope.make(c));
}
// 泛型信息存储库的访问器
private FieldRepository getGenericInfo() {
   
    // 如果需要,延迟初始化存储库
    if (genericInfo == null) {
   
        // 创建和缓存泛型信息存储库
        genericInfo = FieldRepository.make(getGenericSignature(),
                                           getFactory());
    }
    return genericInfo; //return cached repository
}

// 用于在Java代码中实例化这些对象的ReflectAccess使用的包私有构造函数java.lang包通过sun.reflect.LangReflectAccess。
Field(Class<?> declaringClass, String name, Class<?> type, int modifiers, int slot, String signature, byte[] annotations) {
   
    this.clazz = declaringClass;
    this.name = name;
    this.type = type;
    this.modifiers = modifiers;
    this.slot = slot;
    this.signature = signature;
    this.annotations = annotations;
}
// Package-private例程(通过ReflectAccess向java.lang.Class公开)返回此字段的副本。副本的“root”字段指向这个字段。
Field copy() {
   
        // 这个例程允许在引用VM中相同底层方法的Field对象之间共享FieldAccessor对象。(所有这些扭曲都是必要的,因为AccessibleObject中的“可访问性”部分,它隐式地要求为对Class对象的每次反射调用制造新的java.lang.reflect对象。)
    if (this.root != null)
        throw new IllegalArgumentException("Can not copy a non-root Field");

    Field res = new Field(clazz, name, type, modifiers, slot, signature, annotations);
    res.root = this;
    // 如果已经存在,不妨踊跃宣传
    res.fieldAccessor = fieldAccessor;
    res.overrideFieldAccessor = overrideFieldAccessor;

    return res;
}

// 返回由{@code field}对象表示的字段名。
public String getName() {
   
    return name;
}
// 以整数形式返回由{@code field}对象表示的字段的Java语言修饰符。{@code Modifier}类应该用于解码这些修饰符。
public int getModifiers() {
   
    return modifiers;
}
// 如果该字段表示枚举类型的元素,则返回{@code true};否则返回{@code false}。
public boolean isEnumConstant() {
   
    return (getModifiers() & Modifier.ENUM) != 0;
}
// 如果这个字段是一个合成字段,返回{@code true};否则返回{@code false}。
public boolean isSynthetic() {
   
    return Modifier.isSynthetic(getModifiers());
}

// 返回一个{@code Class}对象,该对象标识由{@code field}对象表示的字段声明的类型。
public Class<?> getType() {
   
    return type;
}
// 返回一个{@code Type}对象,该对象表示由该{@code field}对象表示的字段声明的类型。
// 如果{@code Type}是参数化类型,返回的{@code Type}对象必须准确地反映源代码中使用的实际类型参数。如果基础字段的类型是类型变量或参数化类型,则创建该字段。否则,将被解析。
public Type getGenericType() {
   
    if (getGenericSignature() != null)
        return getGenericInfo().getGenericType();
    else
        return getType();
}

// 比较指定对象的{@code Field}。如果两个对象相同,则返回true。两个{@code Field}对象是相同的,如果它们是由同一个类声明的,并且具有相同的名称和类型。
public boolean equals(Object obj) {
   
    if (obj != null && obj instanceof Field) {
   
        Field other = (Field)obj;
        return (getDeclaringClass() == other.getDeclaringClass())
            && (getName() == other.getName())
            && (getType() == other.getType());
    }
    return false;
}
// 返回这个{@code字段}的哈希码。这是作为底层字段声明的类名及其名称的哈希代码的异或计算的。
public int hashCode() {
   
    return getDeclaringClass().getName().hashCode() ^ getName().hashCode();
}

// 返回一个描述这个{@code字段}的字符串。格式是字段的访问修饰符(如果有的话),然后是字段类型,然后是空格,然后是声明字段的类的全限定名称,然后是句点,最后是字段的名称。
// example: public static final int java.lang.Thread.MIN_PRIORITY
public String toString() {
   
    int mod = getModifiers();
    return (((mod == 0) ? "" : (Modifier.toString(mod) + " "))
            + getType().getTypeName() + " "
            + getDeclaringClass().getTypeName() + "."
            + getName());
}
// 返回一个描述这个{@code字段}的字符串,包括它的泛型类型。格式是字段的访问修饰符(如果有的话),然后是泛型字段类型,然后是空格,然后是声明字段的类的全限定名称,然后是句点,最后是字段的名称。
public String toGenericString() {
   
    int mod = getModifiers();
    Type fieldType = getGenericType();
    return (((mod == 0) ? "" : (Modifier.toString(mod) + " "))
            + fieldType.getTypeName() + " "
            + getDeclaringClass().getTypeName() + "."
            + getName());
}

//返回此Field对象的FieldAccessor,而不是从链向上查找到root
private FieldAccessor getFieldAccessor(boolean overrideFinalCheck) {
   
    return (overrideFinalCheck)? overrideFieldAccessor : fieldAccessor;
}
// 为这个Field对象和(递归地)它的root设置FieldAccessor
private void setFieldAccessor(FieldAccessor accessor, boolean overrideFinalCheck) {
   
    if (overrideFinalCheck)
        overrideFieldAccessor = accessor;
    else
        fieldAccessor = accessor;
    // 传播了
    if (root != null) {
   
        root.setFieldAccessor(accessor, overrideFinalCheck);
    }
}
// 注意,这里没有使用同步。为给定的字段生成多个FieldAccessor是正确的(尽管效率不高)。然而,避免同步可能会使实现更具可伸缩性。
private FieldAccessor acquireFieldAccessor(boolean overrideFinalCheck) {
   
    // 首先检查是否已经创建了一个,如果已经创建了,就接受它
    FieldAccessor tmp = null;
    if (root != null) tmp = root.getFieldAccessor(overrideFinalCheck);
    if (tmp != null) {
   
        if (overrideFinalCheck)
            overrideFieldAccessor = tmp;
        else
            fieldAccessor = tmp;
    } else {
   
        // 否则,制造一个并传播到root
        tmp = reflectionFactory.newFieldAccessor(this, overrideFinalCheck);
        setFieldAccessor(tmp, overrideFinalCheck);
    }

    return tmp;
}
// 在调用此方法之前完成安全检查
private FieldAccessor getFieldAccessor(Object obj) throws IllegalAccessException {
   
    boolean ov = override;
    FieldAccessor a = (ov) ? overrideFieldAccessor : fieldAccessor;
    return (a != null) ? a : acquireFieldAccessor(ov);
}
// 返回指定对象上由{@code field}表示的字段的值。如果该值具有基元类型,则该值自动包装在对象中。
public Object get(Object obj) throws IllegalArgumentException, IllegalAccessException {
   
    if (!override) {
   
        if (!Reflection.quickCheckMemberAccess(clazz, modifiers)) {
   
            Class<?> caller =
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值