Constructor、Method、Field 源碼閱讀

AnnotatedElement

/**
 * AnnotatedElement 接口表示目前正在此 VM 中運行的應用程序的一個已註解元素【類、方法、屬性】。
 * 該接口允許反射性地讀取註解。此接口中方法返回的所有註解都是不可變並且可序列化的。
 */
public interface AnnotatedElement {
    /**
     *  該註解元素上是否有指定的註解存在
     */
    default boolean isAnnotationPresent(Class<? extends Annotation> annotationClass) {
        return getAnnotation(annotationClass) != null;
    }

    /**
     *  獲取該註解元素上的指定註解
     */
    <T extends Annotation> T getAnnotation(Class<T> annotationClass);

    /**
     *  獲取該註解元素上的所有註解
     */
    Annotation[] getAnnotations();

    /**
     *  獲取該註解元素上的所有重複註解,並返回該註解的一個數組。
     *
     * @param <T>:註解的類型
     * @param annotationClass:指定註解的 Class 對象
     * @since 1.8
     */
    default <T extends Annotation> T[] getAnnotationsByType(Class<T> annotationClass) {
        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;
    }

    /**
     *  獲取直接聲明在指定類型上的目標註解,不會從父類查找。
     *
     * @param <T>:註解的類型
     * @param annotationClass:註解的 Class 對象
     * @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);
    }

    /**
     *  返回直接聲明在此元素上的所有註解,該方法將忽略繼承的註解。
     */
    Annotation[] getDeclaredAnnotations();
}

Constructor

  • 屬性說明
/**
 * Constructor 對象提供類的單個構造方法的信息【參數列表、返回值、訪問權限等】
 * @since 1.1
 */
public final class Constructor<T> extends Executable {
    // 構造方法聲明的類型
    private final Class<T>            clazz;
    // 內存槽位置
    private final int                 slot;
    // 構造方法的參數類型列表
    private final Class<?>[]          parameterTypes;
    // 構造方法的異常類型列表
    private final Class<?>[]          exceptionTypes;
    // 構造方法的修飾符
    private final int                 modifiers;
    // 泛型和註解支持
    private transient String    signature;
    // 延遲初始化的泛型信息倉庫
    private transient ConstructorRepository genericInfo;
    // 構造方法上的註解
    private final byte[]              annotations;
    // 構造方法的形參註解
    private final byte[]              parameterAnnotations;
    private volatile ConstructorAccessor constructorAccessor;
  • 常用方法
    /**
     *  讀取此構造方法的所在類型
     */
    @Override
    public Class<T> getDeclaringClass() {
        return clazz;
    }

    /**
     *  讀取此構造方法的名稱
     */
    @Override
    public String getName() {
        return getDeclaringClass().getName();
    }

    /**
     *  讀取此構造方法的訪問修飾符
     */
    @Override
    public int getModifiers() {
        return modifiers;
    }

    /**
     *  讀取此構造方法的參數類型列表
     */
    @Override
    public Class<?>[] getParameterTypes() {
        return parameterTypes.clone();
    }

    /**
     *  讀取此構造方法的參數個數
     */
    public int getParameterCount() {
        return parameterTypes.length;
    }

    /**
     *  讀取此構造方法的異常類型數組
     */
    @Override
    public Class<?>[] getExceptionTypes() {
        return exceptionTypes.clone();
    }

    /**
     *  獲取聲明在此構造函數上指定類型的註解
     */
    public <T extends Annotation> T getAnnotation(Class<T> annotationClass) {
        return super.getAnnotation(annotationClass);
    }

    /**
     *  獲取聲明在此構造函數上的所有註解
     */
    public Annotation[] getDeclaredAnnotations()  {
        return super.getDeclaredAnnotations();
    }

    /**
     *  獲取聲明在此構造函數參數列表上的所有註解
     */
    @Override
    public Annotation[][] getParameterAnnotations() {
        return sharedGetParameterAnnotations(parameterTypes, parameterAnnotations);
    }

    /**
     *  設置此構造函數的訪問權限
     */
    @Override
    @CallerSensitive
    public void setAccessible(boolean flag) {
        AccessibleObject.checkPermission();
        if (flag) {
            checkCanSetAccessible(Reflection.getCallerClass());
        }
        setAccessible0(flag);
    }

    /**
     *  基於此構造函數和具體參數創建對象實例
     */
    @CallerSensitive
    @ForceInline // to ensure Reflection.getCallerClass optimization
    public T newInstance(Object ... initargs)
            throws InstantiationException, IllegalAccessException,
            IllegalArgumentException, InvocationTargetException
    {
        if (!override) {
            final Class<?> caller = Reflection.getCallerClass();
            checkAccess(caller, clazz, clazz, modifiers);
        }
        if ((clazz.getModifiers() & Modifier.ENUM) != 0) {
            throw new IllegalArgumentException("Cannot reflectively create enum objects");
        }
        ConstructorAccessor ca = constructorAccessor;   // read volatile
        if (ca == null) {
            ca = acquireConstructorAccessor();
        }
        @SuppressWarnings("unchecked")
        final
        T inst = (T) ca.newInstance(initargs);
        return inst;
    }

Method

  • 字段說明
/**
 * Method 對象提供關於類或接口上單獨某個方法(以及如何訪問該方法)的信息。
 * Method 允許在匹配要調用的實參與底層方法的形參時進行擴展轉換;但如果要進行收縮轉換,則會拋出 IllegalArgumentException。
 */
public final class Method extends Executable {
    // 此方法所聲明類的 Class 對象
    private Class<?>            clazz;
    // 存儲的內存槽
    private int                 slot;
    // 方法的名稱
    private String              name;
    // 方法的返回值類型
    private Class<?>            returnType;
    // 參數類型列表
    private Class<?>[]          parameterTypes;
    // 異常類型列表
    private Class<?>[]          exceptionTypes;
    // 訪問修飾符
    private int                 modifiers;
    // 泛型方法簽名
    private transient String              signature;
    // generic info repository; lazily initialized
    private transient MethodRepository genericInfo;
    // 方法註解
    private byte[]              annotations;
    // 參數註解
    private byte[]              parameterAnnotations;
    private byte[]              annotationDefault;
    // 方法訪問器
    private volatile MethodAccessor methodAccessor;
  • 常用方法
    /**
     *  獲取此方法所在的類型
     */
    @Override
    public Class<?> getDeclaringClass() {
        return clazz;
    }

    /**
     *  讀取此方法的返回類型
     */
    public Class<?> getReturnType() {
        return returnType;
    }

    /**
     *  讀取此方法的訪問修飾符
     */
    @Override
    public int getModifiers() {
        return modifiers;
    }

    /**
     *  讀取方法名稱
     */
    @Override
    public String getName() {
        return name;
    }

    /**
     *  讀取此方法的參數類型列表
     */
    @Override
    public Class<?>[] getParameterTypes() {
        return parameterTypes.clone();
    }

    /**
     *  讀取此方法的參數個數
     * @since 1.8
     */
    public int getParameterCount() {
        return parameterTypes.length;
    }

    /**
     *  讀取此方法的異常類型數組
     */
    @Override
    public Class<?>[] getExceptionTypes() {
        return exceptionTypes.clone();
    }

    /**
     *  讀取此方法上聲明的指定類型的註解
     * @since 1.5
     */
    public <T extends Annotation> T getAnnotation(Class<T> annotationClass) {
        return super.getAnnotation(annotationClass);
    }

    /**
     *  讀取此方法上聲明的所有註解
     * @since 1.5
     */
    public Annotation[] getDeclaredAnnotations()  {
        return super.getDeclaredAnnotations();
    }

    /**
     *  讀取此方法的形參上聲明的所有註解
     */
    @Override
    public Annotation[][] getParameterAnnotations() {
        return sharedGetParameterAnnotations(parameterTypes, parameterAnnotations);
    }

    /**
     *  讀取此方法返回類型上的註解信息
     * @since 1.8
     */
    @Override
    public AnnotatedType getAnnotatedReturnType() {
        return getAnnotatedReturnType0(getGenericReturnType());
    }

    /**
     *  獲取泛型方法的實際返回類型
     */
    public Type getGenericReturnType() {
        if (getGenericSignature() != null) {
            return getGenericInfo().getReturnType();
        } else {
            return getReturnType();
        }
    }

    /**
     *  按聲明順序返回此方法的形參類型列表。
     *  如果形參類型是參數化類型,則爲其返回的 Type 對象必須實際反映源代碼中使用的實際參數的類型。
     */
    @Override
    public Type[] getGenericParameterTypes() {
        return super.getGenericParameterTypes();
    }

    /**
     *  設置方法的訪問權限
     */
    @Override
    @CallerSensitive
    public void setAccessible(boolean flag) {
        AccessibleObject.checkPermission();
        if (flag) {
            checkCanSetAccessible(Reflection.getCallerClass());
        }
        setAccessible0(flag);
    }

    /**
     *  執行目標對象 obj 的此方法,並傳入指定的參數
     */
    @CallerSensitive
    @ForceInline // to ensure Reflection.getCallerClass optimization
    @HotSpotIntrinsicCandidate
    public Object invoke(Object obj, Object... args)
            throws IllegalAccessException, IllegalArgumentException,
            InvocationTargetException
    {
        if (!override) {
            final Class<?> caller = Reflection.getCallerClass();
            checkAccess(caller, clazz,
                    Modifier.isStatic(modifiers) ? null : obj.getClass(),
                            modifiers);
        }
        MethodAccessor ma = methodAccessor;             // read volatile
        if (ma == null) {
            ma = acquireMethodAccessor();
        }
        return ma.invoke(obj, args);
    }

Field

  • 字段說明
/**
 * Field 對象提供類或接口上單個屬性的信息,以及對它的動態訪問權限,屬性可以是類(靜態)屬性和實例(非靜態)屬性。
 * Field 允許在執行 get 或 set 訪問操作期間進行擴展轉換;但如果要進行收縮轉換,則會拋出 IllegalArgumentException。
 * @since 1.1
 */
public final class Field extends AccessibleObject implements Member {
    // 此屬性所在類的 Class 對象
    private Class<?>            clazz;
    // 屬性存儲的內存槽
    private int                 slot;
    // 屬性的名稱
    private String              name;
    // 屬性的類型
    private Class<?>            type;
    // 屬性的訪問修飾符
    private int                 modifiers;
    // 用於支持泛型和註解的簽名
    private transient String    signature;
    // generic info repository; lazily initialized
    private transient FieldRepository genericInfo;
    // 屬性上的註解
    private byte[]              annotations;
    // 緩存的屬性訪問器
    private FieldAccessor fieldAccessor;
    // 被重載的緩存的屬性訪問器
    private FieldAccessor overrideFieldAccessor;
  • 常用方法
    /**
     *  此字段所在的 Class 類型
     */
    @Override
    public Class<?> getDeclaringClass() {
        return clazz;
    }

    /**
     *  此字段的訪問修飾符
     */
    public int getModifiers() {
        return modifiers;
    }

    /**
     *  此字段的名稱
     */
    public String getName() {
        return name;
    }

    /**
     *  讀取此屬性上指定類型的運行時註解
     * @since 1.5
     */
    public <T extends Annotation> T getAnnotation(Class<T> annotationClass) {
        Objects.requireNonNull(annotationClass);
        return annotationClass.cast(declaredAnnotations().get(annotationClass));
    }

    /**
     *  讀取此屬性上聲明的所有註解,忽略繼承的註解
     */
    public Annotation[] getDeclaredAnnotations()  {
        return AnnotationParser.toArray(declaredAnnotations());
    }

    /**
     *  讀取此屬性上指定類型的運行時註解,此註解可重複,包括直接的和繼承的
     * @since 1.8
     */
    @Override
    public <T extends Annotation> T[] getAnnotationsByType(Class<T> annotationClass) {
        Objects.requireNonNull(annotationClass);
        return AnnotationSupport.getDirectlyAndIndirectlyPresent(declaredAnnotations(), annotationClass);
    }

    /** 
     *  設置屬性的訪問權限
     */
    @Override
    @CallerSensitive
    public void setAccessible(boolean flag) {
        AccessibleObject.checkPermission();
        if (flag) {
            checkCanSetAccessible(Reflection.getCallerClass());
        }
        setAccessible0(flag);
    }

    /**
     *  返回此屬性的聲明類型。
     *  如果 Type 是一個參數化類型,則返回的 Type 對象必須準確地反映源代碼中使用的實際類型參數。
     * @since 1.5
     */
    public Type getGenericType() {
        if (getGenericSignature() != null) {
            return getGenericInfo().getGenericType();
        }
        else {
            return getType();
        }
    }

    /**
     *  讀取目標對象 obj 的此屬性值
     * @throws IllegalArgumentException 目標對象未聲明該屬性
     * @throws IllegalAccessException 該屬性受訪問限制
     */
    @CallerSensitive
    @ForceInline // to ensure Reflection.getCallerClass optimization
    public Object get(Object obj)
        throws IllegalArgumentException, IllegalAccessException
    {
        if (!override) {
            Class<?> caller = Reflection.getCallerClass();
            checkAccess(caller, obj);
        }
        return getFieldAccessor(obj).get(obj);
    }

    /**
     *  設置目標對象 obj 的屬性值爲 value
     */
    @CallerSensitive
    @ForceInline // to ensure Reflection.getCallerClass optimization
    public void set(Object obj, Object value)
        throws IllegalArgumentException, IllegalAccessException
    {
        if (!override) {
            Class<?> caller = Reflection.getCallerClass();
            checkAccess(caller, obj);
        }
        getFieldAccessor(obj).set(obj, value);
    }
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章