超详细的逐句介绍Java反射之Field类和InvocationTargetException类函数源码讲解(全)

一、Field类和InvocationTargetException类

InvocationTargetException 是一个经过检查的异常,它包装了被调用的方法或构造函数抛出的异常。Field提供有关类或接口的单个​​字段的信息和动态访问。反射字段可以是类(静态)字段或实例字段。下面我将从源码角度详细介绍Field类和InvocationTargetException类内部源码

二、Field类源码介绍

Field类继承了AccessibleObject类,同时实现了接口Member

public final
class Field extends AccessibleObject implements Member {
     
}

下面定义了一些基本变量

	private Class<?>            clazz;
    private int                 slot;
    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;
    private Field               root;

获取泛型签名

private String getGenericSignature() {
     return signature;}

获取泛型工厂

private GenericsFactory getFactory() {
     
        Class<?> c = getDeclaringClass();
        // create scope and factory
        return CoreReflectionFactory.make(c, ClassScope.make(c));
    }

获取字段存储库

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

Field的构造方法

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;
    }

包私有例程(通过 ReflectAccess 暴露给 java.lang.Class)返回该字段的副本。 副本的“根”字段指向此字段。

Field copy() {
     

        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;
    }

返回表示类或接口的 Class 对象,该类或接口声明了由此 Field 对象表示的字段

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

获取字段名称

public String getName() {
     
        return name;
    }

获取修饰符

public int getModifiers() {
     
        return modifiers;
    }

判断是否是枚举

public boolean isEnumConstant() {
     
        return (getModifiers() & Modifier.ENUM) != 0;
    }

判断是否是合成字段

public boolean isSynthetic() {
     
        return Modifier.isSynthetic(getModifiers());
    }

定义获取类型

public Class<?> getType() {
     
        return type;
    }

获取泛型类型

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

将此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;
    }

获取哈希值

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

定义返回描述此Field的字符串

public String toString() {
     
        int mod = getModifiers();
        return (((mod == 0) ? "" : (Modifier.toString(mod) + " "))
            + getType().getTypeName() + " "
            + getDeclaringClass().getTypeName() + "."
            + getName());
    }

转化为泛型字符串

public String toGenericString() {
     
        int mod = getModifiers();
        Type fieldType = getGenericType();
        return (((mod == 0) ? "" : (Modifier.toString(mod) + " "))
            + fieldType.getTypeName() + " "
            + getDeclaringClass().getTypeName() + "."
            + getName());
    }

在指定的对象上返回由此 Field 表示的字段的值。

 public Object get(Object obj)
        throws IllegalArgumentException, IllegalAccessException
    {
     
        if (!override) {
     
            if (!Reflection.quickCheckMemberAccess(clazz, modifiers)) {
     
                Class<?> caller = Reflection.getCallerClass();
                checkAccess(caller, clazz, obj, modifiers);
            }
        }
        return getFieldAccessor(obj).get(obj);
    }

获取静态或实例布尔字段的值。

public boolean getBoolean(Object obj)
        throws IllegalArgumentException, IllegalAccessException
    {
     
        if (!override) {
     
            if (!Reflection.quickCheckMemberAccess(clazz, modifiers)) {
     
                Class<?> caller = Reflection.getCallerClass();
                checkAccess(caller, clazz, obj, modifiers);
            }
        }
        return getFieldAccessor(obj).getBoolean(obj);
    }

获取静态或实例字节字段的不同类型的值。

public byte getByte(Object obj)
        throws IllegalArgumentException, IllegalAccessException
    {
     
        if (!override) {
     
            if (!Reflection.quickCheckMemberAccess(clazz, modifiers)) {
     
                Class<?> caller = Reflection.getCallerClass();
                checkAccess(caller, clazz, obj, modifiers);
            }
        }
        return getFieldAccessor(obj).getByte(obj);
    }
public char getChar(Object obj)
        throws IllegalArgumentException, IllegalAccessException
    {
     
        if (!override) {
     
            if (!Reflection.quickCheckMemberAccess(clazz, modifiers)) {
     
                Class<?> caller = Reflection.getCallerClass();
                checkAccess(caller, clazz, obj, modifiers);
            }
        }
        return getFieldAccessor(obj).getChar(obj);
    }
public short getShort(Object obj)
        throws IllegalArgumentException, IllegalAccessException
    {
     
        if (!override) {
     
            if (!Reflection.quickCheckMemberAccess(clazz, modifiers)) {
     
                Class<?> caller = Reflection.getCallerClass();
                checkAccess(caller, clazz, obj, modifiers);
            }
        }
        return getFieldAccessor(obj).getShort(obj);
    }
 public int getInt(Object obj)
        throws IllegalArgumentException, IllegalAccessException
    {
     
        if (!override) {
     
            if (!Reflection.quickCheckMemberAccess(clazz, modifiers)) {
     
                Class<?> caller = Reflection.getCallerClass();
                checkAccess(caller, clazz, obj, modifiers);
            }
        }
        return getFieldAccessor(obj).getInt(obj);
    }
public long getLong(Object obj)
        throws IllegalArgumentException, IllegalAccessException
    {
     
        if (!override) {
     
            if (!Reflection.quickCheckMemberAccess(clazz, modifiers)) {
     
                Class<?> caller = Reflection.getCallerClass();
                checkAccess(caller, clazz, obj, modifiers);
            }
        }
        return getFieldAccessor(obj).getLong(obj);
    }
public float getFloat(Object obj)
        throws IllegalArgumentException, IllegalAccessException
    {
     
        if (!override) {
     
            if (!Reflection.quickCheckMemberAccess(clazz, modifiers)) {
     
                Class<?> caller = Reflection.getCallerClass();
                checkAccess(caller, clazz, obj, modifiers);
            }
        }
        return getFieldAccessor(obj).getFloat(obj);
    }
public double getDouble(Object obj)
        throws IllegalArgumentException, IllegalAccessException
    {
     
        if (!override) {
     
            if (!Reflection.quickCheckMemberAccess(clazz, modifiers)) {
     
                Class<?> caller = Reflection.getCallerClass();
                checkAccess(caller, clazz, obj, modifiers);
            }
        }
        return getFieldAccessor(obj).getDouble(obj);
    }
    

设置某个对象的值。

 public void set(Object obj, Object value)
        throws IllegalArgumentException, IllegalAccessException
    {
     
        if (!override) {
     
            if (!Reflection.quickCheckMemberAccess(clazz, modifiers)) {
     
                Class<?> caller = Reflection.getCallerClass();
                checkAccess(caller, clazz, obj, modifiers);
            }
        }
        getFieldAccessor(obj).set(obj, value);
    }

设置某个对象的布尔类型

public void setBoolean(Object obj, boolean z)
        throws IllegalArgumentException, IllegalAccessException
    {
     
        if (!override) {
     
            if (!Reflection.quickCheckMemberAccess(clazz, modifiers)) {
     
                Class<?> caller = Reflection.getCallerClass();
                checkAccess(caller, clazz, obj, modifiers);
            }
        }
        getFieldAccessor(obj).setBoolean(obj, z);
    }

设置某个对象的byte类型字

public void setByte(Object obj, byte b)
        throws IllegalArgumentException, IllegalAccessException
    {
     
        if (!override) {
     
            if (!Reflection.quickCheckMemberAccess(clazz, modifiers)) {
     
                Class<?> caller = Reflection.getCallerClass();
                checkAccess(caller, clazz, obj, modifiers);
            }
        }
        getFieldAccessor(obj).setByte(obj, b);
    }

设置某个对象的char类型字

 public void setChar(Object obj, char c)
        throws IllegalArgumentException, IllegalAccessException
    {
     
        if (!override) {
     
            if (!Reflection.quickCheckMemberAccess(clazz, modifiers)) {
     
                Class<?> caller = Reflection.getCallerClass();
                checkAccess(caller, clazz, obj, modifiers);
            }
        }
        getFieldAccessor(obj).setChar(obj, c);
    }

设置某个对象的short类型字

 public void setShort(Object obj, short s)
        throws IllegalArgumentException, IllegalAccessException
    {
     
        if (!override) {
     
            if (!Reflection.quickCheckMemberAccess(clazz, modifiers)) {
     
                Class<?> caller = Reflection.getCallerClass();
                checkAccess(caller, clazz, obj, modifiers);
            }
        }
        getFieldAccessor(obj).setShort(obj, s);
    }

设置某个对象的int类型字

 public void setInt(Object obj, int i)
        throws IllegalArgumentException, IllegalAccessException
    {
     
        if (!override) {
     
            if (!Reflection.quickCheckMemberAccess(clazz, modifiers)) {
     
                Class<?> caller = Reflection.getCallerClass();
                checkAccess(caller, clazz, obj, modifiers);
            }
        }
        getFieldAccessor(obj).setInt(obj, i);
    }

设置某个对象的long类型字

 public void setLong(Object obj, long l)
        throws IllegalArgumentException, IllegalAccessException
    {
     
        if (!override) {
     
            if (!Reflection.quickCheckMemberAccess(clazz, modifiers)) {
     
                Class<?> caller = Reflection.getCallerClass();
                checkAccess(caller, clazz, obj, modifiers);
            }
        }
        getFieldAccessor(obj).setLong(obj, l);
    }

设置某个对象的float类型字

public void setFloat(Object obj, float f)
        throws IllegalArgumentException, IllegalAccessException
    {
     
        if (!override) {
     
            if (!Reflection.quickCheckMemberAccess(clazz, modifiers)) {
     
                Class<?> caller = Reflection.getCallerClass();
                checkAccess(caller, clazz, obj, modifiers);
            }
        }
        getFieldAccessor(obj).setFloat(obj, f);
    }

设置某个对象的double类型字

public void setDouble(Object obj, double d)
        throws IllegalArgumentException, IllegalAccessException
    {
     
        if (!override) {
     
            if (!Reflection.quickCheckMemberAccess(clazz, modifiers)) {
     
                Class<?> caller = Reflection.getCallerClass();
                checkAccess(caller, clazz, obj, modifiers);
            }
        }
        getFieldAccessor(obj).setDouble(obj, d);
    }

获取字段地址,中间为具体实现类,最后是对外接口类

private FieldAccessor getFieldAccessor(Object obj)
        throws IllegalAccessException
    {
     
        boolean ov = override;
        FieldAccessor a = (ov) ? overrideFieldAccessor : fieldAccessor;
        return (a != null) ? a : acquireFieldAccessor(ov);
    }
private FieldAccessor acquireFieldAccessor(boolean overrideFinalCheck) {
     
        // First check to see if one has been created yet, and take it
        // if so
        FieldAccessor tmp = null;
        if (root != null) tmp = root.getFieldAccessor(overrideFinalCheck);
        if (tmp != null) {
     
            if (overrideFinalCheck)
                overrideFieldAccessor = tmp;
            else
                fieldAccessor = tmp;
        } else {
     
            // Otherwise fabricate one and propagate it up to the root
            tmp = reflectionFactory.newFieldAccessor(this, overrideFinalCheck);
            setFieldAccessor(tmp, overrideFinalCheck);
        }

        return tmp;
    }
private FieldAccessor getFieldAccessor(boolean overrideFinalCheck) {
     
        return (overrideFinalCheck)? overrideFieldAccessor : fieldAccessor;
    }

设置字段地址

private void setFieldAccessor(FieldAccessor accessor, boolean overrideFinalCheck) {
     
        if (overrideFinalCheck)
            overrideFieldAccessor = accessor;
        else
            fieldAccessor = accessor;
        // Propagate up
        if (root != null) {
     
            root.setFieldAccessor(accessor, overrideFinalCheck);
        }
    }

定于注解类型

public <T extends Annotation> T getAnnotation(Class<T> annotationClass) {
     
        Objects.requireNonNull(annotationClass);
        return annotationClass.cast(declaredAnnotations().get(annotationClass));
    }

定义获取注解类型

public <T extends Annotation> T[] getAnnotationsByType(Class<T> annotationClass) {
     
        Objects.requireNonNull(annotationClass);

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

返回直接出现在此元素上的注释## 三、InvocationTargetException类源码介绍
InvocationTargetException类

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

定义注解泛型和注解键值对

private transient Map<Class<? extends Annotation>, Annotation> declaredAnnotations;

生成泛型-注解键值对

private synchronized  Map<Class<? extends Annotation>, Annotation> declaredAnnotations() {
     
        if (declaredAnnotations == null) {
     
            Field root = this.root;
            if (root != null) {
     
                declaredAnnotations = root.declaredAnnotations();
            } else {
     
                declaredAnnotations = AnnotationParser.parseAnnotations(
                        annotations,
                        sun.misc.SharedSecrets.getJavaLangAccess().getConstantPool(getDeclaringClass()),
                        getDeclaringClass());
            }
        }
        return declaredAnnotations;
    }

调用JVM获取注解byte数组

private native byte[] getTypeAnnotationBytes0();

定义获取注解类型对外接口类

public AnnotatedType getAnnotatedType() {
     
        return TypeAnnotationParser.buildAnnotatedType(getTypeAnnotationBytes0(),
                                                       sun.misc.SharedSecrets.getJavaLangAccess().
                                                           getConstantPool(getDeclaringClass()),
                                                       this,
                                                       getDeclaringClass(),
                                                       getGenericType(),
                                                       TypeAnnotation.TypeAnnotationTarget.FIELD);
}

三、InvocationTargetException类

InvocationTargetException类继承了ReflectiveOperationException类

public class InvocationTargetException extends ReflectiveOperationException {
     
}

下面定义了通用串行ID

private static final long serialVersionUID = 4085088731926701167L;

返回目标

private Throwable target;

构造一个以 null 作为目标异常的 InvocationTargetException。

protected InvocationTargetException() {
     
        super((Throwable)null);

构造一个带有目标异常的 InvocationTargetException。

public InvocationTargetException(Throwable target) {
     
        super((Throwable)null);  // Disallow initCause
        this.target = target;
    }

构造一个带有目标异常和详细消息的 InvocationTargetException

public InvocationTargetException(Throwable target, String s) {
     
        super(s, null);  // Disallow initCause
        this.target = target;
    }

获取抛出的目标异常

public Throwable getTargetException() {
     
        return target;
    }

返回此异常的原因(抛出的目标异常,可能为null

public Throwable getCause() {
     
        return target;
    }

你可能感兴趣的