java反射学习笔记(二)—— Class及Method等常用类

2019-04-23  本文已影响0人  翌oo

[TOC]

1.Class

每个类运行时的类型信息就是用Class对象来表示的,它包含了与类有关的信息,获得运行时类的信息都需要通过这个Class对象来实现。
Class类没有公共的构造方法,Class对象是在类加载时候由JVM虚拟机以及通过调用类加载器中的defineClass方法自动构造的。

如何获得Class对象

public final class Class<T> implements java.io.Serializable,
                              GenericDeclaration,
                              Type,
                              AnnotatedElement {
}

Class类中提供了很多方法方便获取到类的信息,常用的比如说方法和域。下面就说一下Method和Field类。

2.Method

Method类主要用于程序运行状态中,动态的获取方法信息。通常通过class.getmethods,getMethod方法获得。

Method常用方法

public final class Method extends Executable {
    @Override
    //获取一个AnnotatedType对象,该对象表示该方法的返回类型。
    public AnnotatedType getAnnotatedReturnType() {
        return getAnnotatedReturnType0(getGenericReturnType());
    }
    public Class<?> getReturnType() {
        return returnType;
    }
    //获取方法的参数
    public TypeVariable<Method>[] getTypeParameters() {
        if (getGenericSignature() != null)
            return (TypeVariable<Method>[])getGenericInfo().getTypeParameters();
        else
            return (TypeVariable<Method>[])new TypeVariable[0];
    }
    public Class<?>[] getParameterTypes() {
        return parameterTypes.clone();
    }
    public Type[] getGenericParameterTypes() {
        return super.getGenericParameterTypes();
    }
    
    //动态代理中会使用该方法
    @CallerSensitive
    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);
    }
}

3.Field

Field描述的是类的属性信息,可以用来获取当前对象的成员变量的类型以及对成员变量重新设值。

获取field类对象的方法:

Field常用方法

public final class Field extends AccessibleObject implements Member {
    //返回这个变量的类型
    public Class<?> getType() {
        return type;
    }
    //返回指定对象obj上此Field表示的字段的值
    public Object get(Object obj)
        throws IllegalArgumentException, IllegalAccessException
    {
        return getFieldAccessor(obj).get(obj);
    }
    //将指定对象变量上此Field对象表示的字段设置为指定的新值。
    public void set(Object obj, Object value)
        throws IllegalArgumentException, IllegalAccessException
    {
        getFieldAccessor(obj).set(obj, value);
    }
}
上一篇 下一篇

猜你喜欢

热点阅读