一、Constructort类和Method类

Constructort类构造函数提供有关类的单个构造函数的信息和对其的访问。Method类方法提供有关类或接口上的单个方法的信息和对其的访问。反映的方法可以是类方法或实例方法(包括抽象方法)。下面我将从源码的角度对这两个类进行详细介绍。

二、Constructort类源码介绍

Constructort类继承了Executable类

public final class Constructor<T> extends Executable {
}

下面定义了一些基本变量

private Class<T>            clazz;
    private int                 slot;
    private Class<?>[]          parameterTypes;
    private Class<?>[]          exceptionTypes;
    private int                 modifiers;
    // Generics and annotations support
    private transient String    signature;
    // generic info repository; lazily initialized
    private transient ConstructorRepository genericInfo;
    private byte[]              annotations;
    private byte[]              parameterAnnotations;

定义泛型工厂

private GenericsFactory getFactory() {
        // create scope and factory
        return CoreReflectionFactory.make(this, ConstructorScope.make(this));
    }

定义了获取基本信息的方法

ConstructorRepository getGenericInfo() {
        // lazily initialize repository if necessary
        if (genericInfo == null) {
            // create and cache generic info repository
            genericInfo =
                ConstructorRepository.make(getSignature(),
                                           getFactory());
        }
        return genericInfo; //return cached repository
    }

定义了一个转瞬即逝的构造地址

private volatile ConstructorAccessor constructorAccessor;

定义一个管理员的构造者

private Constructor<T>      root;

获取root权限

Executable getRoot() {
        return root;
    }

构造私有的重写方法

Constructor(Class<T> declaringClass,
                Class<?>[] parameterTypes,
                Class<?>[] checkedExceptions,
                int modifiers,
                int slot,
                String signature,
                byte[] annotations,
                byte[] parameterAnnotations) {
        this.clazz = declaringClass;
        this.parameterTypes = parameterTypes;
        this.exceptionTypes = checkedExceptions;
        this.modifiers = modifiers;
        this.slot = slot;
        this.signature = signature;
        this.annotations = annotations;
        this.parameterAnnotations = parameterAnnotations;
    }

定义复制方法

Constructor<T> copy() {
      
        if (this.root != null)
            throw new IllegalArgumentException("Can not copy a non-root Constructor");

        Constructor<T> res = new Constructor<>(clazz,
                                               parameterTypes,
                                               exceptionTypes, modifiers, slot,
                                               signature,
                                               annotations,
                                               parameterAnnotations);
        res.root = this;
        // Might as well eagerly propagate this if already present
        res.constructorAccessor = constructorAccessor;
        return res;
    }

定义是否含有通用信息

boolean hasGenericInformation() {
        return (getSignature() != null);
    }

获取注解信息

byte[] getAnnotationBytes() {
        return annotations;
    }

返回表示类或接口的 Class 对象,该类或接口声明了由此对象表示的可执行文件

public Class<T> getDeclaringClass() {
        return clazz;
    }

定义获取类或接口的 Class 对象的名称

public String getName() {
        return getDeclaringClass().getName();
    }

获取类或接口的 Class 对象的修饰符

public int getModifiers() {
        return modifiers;
    }

定义获取参数列表类型

public TypeVariable<Constructor<T>>[] getTypeParameters() {
      if (getSignature() != null) {
        return (TypeVariable<Constructor<T>>[])getGenericInfo().getTypeParameters();
      } else
          return (TypeVariable<Constructor<T>>[])new TypeVariable[0];
    }

获取具体参数类型

public Class<?>[] getParameterTypes() {
        return parameterTypes.clone();
    }

获取参数列表长度

public int getParameterCount() { return parameterTypes.length; }

获取类或者接口对象的参数列表

public Type[] getGenericParameterTypes() {
        return super.getGenericParameterTypes();
    }

获取其他类型

public Class<?>[] getExceptionTypes() {
        return exceptionTypes.clone();
    }

或接口对象其他类型

public Type[] getGenericExceptionTypes() {
        return super.getGenericExceptionTypes();
    }

判断是否相等方法

public boolean equals(Object obj) {
        if (obj != null && obj instanceof Constructor) {
            Constructor<?> other = (Constructor<?>)obj;
            if (getDeclaringClass() == other.getDeclaringClass()) {
                return equalParamTypes(parameterTypes, other.parameterTypes);
            }
        }
        return false;
    }

获取hash码

public int hashCode() {
        return getDeclaringClass().getName().hashCode();
    }

转化为字符串方法

public String toString() {
        return sharedToString(Modifier.constructorModifiers(),
                              false,
                              parameterTypes,
                              exceptionTypes);
    }
   void specificToStringHeader(StringBuilder sb) {
        sb.append(getDeclaringClass().getTypeName());
    }

用于获取类名或者接口名

public String toGenericString() {
        return sharedToGenericString(Modifier.constructorModifiers(), false);
    }

    void specificToGenericStringHeader(StringBuilder sb) {
        specificToStringHeader(sb);
    }

定义一个新的实例

public T newInstance(Object ... initargs)
        throws InstantiationException, IllegalAccessException,
               IllegalArgumentException, InvocationTargetException
    {
        if (!override) {
            if (!Reflection.quickCheckMemberAccess(clazz, modifiers)) {
                Class<?> caller = Reflection.getCallerClass();
                checkAccess(caller, clazz, null, 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")
        T inst = (T) ca.newInstance(initargs);
        return inst;
    }

如果此可执行文件被声明为采用可变数量的参数,则返回 true;否则返回 false。

public boolean isVarArgs() {
        return super.isVarArgs();
    }

如果此可执行文件是合成结构,则返回 true;否则返回 false

public boolean isSynthetic() {
        return super.isSynthetic();
    }

构造地址的构造者,下面是具体实现类

ConstructorAccessor getConstructorAccessor() {
        return constructorAccessor;
    }
private ConstructorAccessor acquireConstructorAccessor() {
        ConstructorAccessor tmp = null;
        if (root != null) tmp = root.getConstructorAccessor();
        if (tmp != null) {
            constructorAccessor = tmp;
        } else {
            // Otherwise fabricate one and propagate it up to the root
            tmp = reflectionFactory.newConstructorAccessor(this);
            setConstructorAccessor(tmp);
        }

        return tmp;
    }

设置构造地址的构造者

void setConstructorAccessor(ConstructorAccessor accessor) {
        constructorAccessor = accessor;
        // Propagate up
        if (root != null) {
            root.setConstructorAccessor(accessor);
        }
    }

下面定义了一些获取状态的方法

int getSlot() {
        return slot;
    }

    String getSignature() {
        return signature;
    }

    byte[] getRawAnnotations() {
        return annotations;
    }

    byte[] getRawParameterAnnotations() {
        return parameterAnnotations;
    }

下面定义获取注解的方法

public <T extends Annotation> T getAnnotation(Class<T> annotationClass) {
        return super.getAnnotation(annotationClass);
    }

定义获取类或者接口的注解

public Annotation[] getDeclaredAnnotations()  {
        return super.getDeclaredAnnotations();
    }

获取多个类或者接口对象的多个注解

public Annotation[][] getParameterAnnotations() {
        return sharedGetParameterAnnotations(parameterTypes, parameterAnnotations);
    }

定义解决类或者接口没有匹配的解决方法

void handleParameterNumberMismatch(int resultLength, int numParameters) {
        Class<?> declaringClass = getDeclaringClass();
        if (declaringClass.isEnum() ||
            declaringClass.isAnonymousClass() ||
            declaringClass.isLocalClass() )
            return ; // Can't do reliable parameter counting
        else {
            if (!declaringClass.isMemberClass() || // top-level
                // Check for the enclosing instance parameter for
                // non-static member classes
                (declaringClass.isMemberClass() &&
                 ((declaringClass.getModifiers() & Modifier.STATIC) == 0)  &&
                 resultLength + 1 != numParameters) ) {
                throw new AnnotationFormatError(
                          "Parameter annotations don't match number of parameters");
            }
        }
    }

下面定义了获取注释类型,下面为具体实现类

public AnnotatedType getAnnotatedReturnType() {
        return getAnnotatedReturnType0(getDeclaringClass());
    }
public AnnotatedType getAnnotatedReceiverType() {
        if (getDeclaringClass().getEnclosingClass() == null)
            return super.getAnnotatedReceiverType();

        return TypeAnnotationParser.buildAnnotatedType(getTypeAnnotationBytes0(),
                sun.misc.SharedSecrets.getJavaLangAccess().
                        getConstantPool(getDeclaringClass()),
                this,
                getDeclaringClass(),
                getDeclaringClass().getEnclosingClass(),
                TypeAnnotation.TypeAnnotationTarget.METHOD_RECEIVER);
    }

三、Method类源码介绍

Method类继承了Executable

public final class Method extends Executable {
}

下面定义了一些变量

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;
    private transient MethodRepository genericInfo;
    private byte[]              annotations;
    private byte[]              parameterAnnotations;
    private byte[]              annotationDefault;
    private volatile MethodAccessor methodAccessor;
    private Method              root;

获取通用签名

private String getGenericSignature() {return signature;}

获取类或者接口

private GenericsFactory getFactory() {
        // create scope and factory
        return CoreReflectionFactory.make(this, MethodScope.make(this));
    }

定义获取类或者的方法库

MethodRepository getGenericInfo() {
        // lazily initialize repository if necessary
        if (genericInfo == null) {
            // create and cache generic info repository
            genericInfo = MethodRepository.make(getGenericSignature(),
                                                getFactory());
        }
        return genericInfo; //return cached repository
    }

Method的内部构造方法

Method(Class<?> declaringClass,
           String name,
           Class<?>[] parameterTypes,
           Class<?> returnType,
           Class<?>[] checkedExceptions,
           int modifiers,
           int slot,
           String signature,
           byte[] annotations,
           byte[] parameterAnnotations,
           byte[] annotationDefault) {
        this.clazz = declaringClass;
        this.name = name;
        this.parameterTypes = parameterTypes;
        this.returnType = returnType;
        this.exceptionTypes = checkedExceptions;
        this.modifiers = modifiers;
        this.slot = slot;
        this.signature = signature;
        this.annotations = annotations;
        this.parameterAnnotations = parameterAnnotations;
        this.annotationDefault = annotationDefault;
    }

方法库的复制方法

Method copy() {
        if (this.root != null)
            throw new IllegalArgumentException("Can not copy a non-root Method");

        Method res = new Method(clazz, name, parameterTypes, returnType,
                                exceptionTypes, modifiers, slot, signature,
                                annotations, parameterAnnotations, annotationDefault);
        res.root = this;
        // Might as well eagerly propagate this if already present
        res.methodAccessor = methodAccessor;
        return res;
    }

定义获取权限方法

Executable getRoot() {
        return root;
    }

判断是否获得类或接口对象的信息

boolean hasGenericInformation() {
        return (getGenericSignature() != null);
    }

定义获取注解并存储进byte数组

byte[] getAnnotationBytes() {
        return annotations;
    }

返回表示类或接口的 Class 对象,该类或接口声明了由此对象表示的可执行文件。

public Class<?> getDeclaringClass() {
        return clazz;
    }

获取类或者接口对象名称

public String getName() {
        return name;
    }

定义获取修饰符函数

public int getModifiers() {
        return modifiers;
    }

获取类型列表

public TypeVariable<Method>[] getTypeParameters() {
        if (getGenericSignature() != null)
            return (TypeVariable<Method>[])getGenericInfo().getTypeParameters();
        else
            return (TypeVariable<Method>[])new TypeVariable[0];
    }

获取返回类型

public Class<?> getReturnType() {
        return returnType;
    }

返回一个 Type 对象,该对象表示此 Method 对象表示的方法的正式返回类型。

public Type getGenericReturnType() {
      if (getGenericSignature() != null) {
        return getGenericInfo().getReturnType();
      } else { return getReturnType();}
    }

返回一个 Class 对象数组,这些对象按声明顺序表示由此对象表示的可执行文件的形式参数类型。如果底层可执行文件不带参数,则返回长度为 0 的数组。

public Class<?>[] getParameterTypes() {
        return parameterTypes.clone();
    }

定义获取参数列表的个数

public int getParameterCount() { return parameterTypes.length; }

返回一个 Type 对象数组,这些对象按声明顺序表示由此对象表示的可执行文件的形式参数类型。

public Type[] getGenericParameterTypes() {
        return super.getGenericParameterTypes();
    }

返回一个 Class 对象数组,这些对象表示声明为由该对象表示的底层可执行文件抛出的异常类型。

public Class<?>[] getExceptionTypes() {
        return exceptionTypes.clone();
    }

返回一个 Type 对象数组,这些对象表示声明为由此可执行对象抛出的异常。

public Type[] getGenericExceptionTypes() {
        return super.getGenericExceptionTypes();
    }

将此方法与指定的对象进行比较。

public boolean equals(Object obj) {
        if (obj != null && obj instanceof Method) {
            Method other = (Method)obj;
            if ((getDeclaringClass() == other.getDeclaringClass())
                && (getName() == other.getName())) {
                if (!returnType.equals(other.getReturnType()))
                    return false;
                return equalParamTypes(parameterTypes, other.parameterTypes);
            }
        }
        return false;
    }

获取哈希值

public int hashCode() {
        return getDeclaringClass().getName().hashCode() ^ getName().hashCode();
    }

获取描述此方法的字符串,下面函数是获取字符串头部

public String toString() {
        return sharedToString(Modifier.methodModifiers(),
                              isDefault(),
                              parameterTypes,
                              exceptionTypes);
    }
void specificToStringHeader(StringBuilder sb) {
        sb.append(getReturnType().getTypeName()).append(' ');
        sb.append(getDeclaringClass().getTypeName()).append('.');
        sb.append(getName());
    }

返回描述此方法的字符串,包括类型参数

public String toGenericString() {
        return sharedToGenericString(Modifier.methodModifiers(), isDefault());
    }
void specificToGenericStringHeader(StringBuilder sb) {
        Type genRetType = getGenericReturnType();
        sb.append(genRetType.getTypeName()).append(' ');
        sb.append(getDeclaringClass().getTypeName()).append('.');
        sb.append(getName());
    }

调用参数列表

public Object invoke(Object obj, Object... args)
        throws IllegalAccessException, IllegalArgumentException,
           InvocationTargetException
    {
        if (!override) {
            if (!Reflection.quickCheckMemberAccess(clazz, modifiers)) {
                Class<?> caller = Reflection.getCallerClass();
                checkAccess(caller, clazz, obj, modifiers);
            }
        }
        MethodAccessor ma = methodAccessor;             // read volatile
        if (ma == null) {
            ma = acquireMethodAccessor();
        }
        return ma.invoke(obj, args);
    }

判断是否是桥接器

public boolean isBridge() {
        return (getModifiers() & Modifier.BRIDGE) != 0;
    }

判断此可执行文件被声明为采用可变数量的参数

public boolean isVarArgs() {
        return super.isVarArgs();
    }

判断此可执行文件是否是合成结构

public boolean isSynthetic() {
        return super.isSynthetic();
    }

判断是否是默认

public boolean isDefault() {
        return ((getModifiers() & (Modifier.ABSTRACT | Modifier.PUBLIC | Modifier.STATIC)) ==
                Modifier.PUBLIC) && getDeclaringClass().isInterface();
    }

获取方法地址,下面是具体实现类

MethodAccessor getMethodAccessor() {
        return methodAccessor;
    }
private MethodAccessor acquireMethodAccessor() {
        MethodAccessor tmp = null;
        if (root != null) tmp = root.getMethodAccessor();
        if (tmp != null) {
            methodAccessor = tmp;
        } else {
            tmp = reflectionFactory.newMethodAccessor(this);
            setMethodAccessor(tmp);
        }

        return tmp;
    }

设置方法地址

void setMethodAccessor(MethodAccessor accessor) {
        methodAccessor = accessor;
        // Propagate up
        if (root != null) {
            root.setMethodAccessor(accessor);
        }
    }

获取默认值

public Object getDefaultValue() {
        if  (annotationDefault == null)
            return null;
        Class<?> memberType = AnnotationType.invocationHandlerReturnType(
            getReturnType());
        Object result = AnnotationParser.parseMemberValue(
            memberType, ByteBuffer.wrap(annotationDefault),
            sun.misc.SharedSecrets.getJavaLangAccess().
                getConstantPool(getDeclaringClass()),
            getDeclaringClass());
        if (result instanceof sun.reflect.annotation.ExceptionProxy)
            throw new AnnotationFormatError("Invalid default: " + this);
        return result;
    }

下面定义了获取注解的方法

public <T extends Annotation> T getAnnotation(Class<T> annotationClass) {
        return super.getAnnotation(annotationClass);
    }

返回直接出现在此元素上的注释,下面可以多个方法的注解

public Annotation[] getDeclaredAnnotations()  {
        return super.getDeclaredAnnotations();
    }
public Annotation[][] getParameterAnnotations() {
        return sharedGetParameterAnnotations(parameterTypes, parameterAnnotations);
    }

定义获取注解类型

public AnnotatedType getAnnotatedReturnType() {
        return getAnnotatedReturnType0(getGenericReturnType());
    }

定义解决类型不匹配的解决方法

void handleParameterNumberMismatch(int resultLength, int numParameters) {
        throw new AnnotationFormatError("Parameter annotations don't match number of parameters");
    }