反射四大核心类:Class、Constructor、Method、 Filed

反射总结
反射四大核心类:Class、Constructor、Method、 Filed

一、Class类:

1.核心操作:Object
    public final native Class<?> getClass();
    返回值:Class类
    Class:反射核心类,描述其他类的结构

2.Class类的三种实例化方式(每一个类的Class的对象有且只有一个,由JVM加载时创建对象)
    a.任意对象.getClass()
    b.类名.class
    c.调用Class的静态方法:Class.forNmae(String className);

3.利用Class对象反射创建类的对象:
    Class类中提供如下方法:
        publci T newInstance() thorows 抛出异常

二、Constructor类:

1.Class提供的newInstance()默认调用类中【无参构造】

2.取得类中构造方法
 public Constructor<T> getConstructor(Class<?> ... parameterTypes)

3.取得类中所有构造
public Constructor<?>[] getConstructors() throws Execption

注意:2和3只能取得修饰符为public的构造方法

4.取得类中所有构造方法与修饰符无关
    public Constructor<T> getDeclaredConstructor()

    public Constructor<?>[] getDeclaredConstructors()

    // 破坏封装
    setAccessible(boolean);

三、Method类:

1.取得所有普通方法
    Method[] getMethods() throws SecurityException
    返回本类及父类的所有public普通方法

    getDeclaredMethods()
    返回本类所有普通方法,与修饰符无关

2.取得指定方法
    public Method getMethod(方法名,方法参数)
    返回【本类及父类】的所有public普通方法

    public Method getDeclaredMethod(方法名,方法参数)
    返回【本类】所有普通方法,与修饰符无关

3.调用
    Method提供的
    public Object invoke(类的实例化对象,方法具体参数)

例子:
public static void main(String[] args) throws Exception{
        // 取得Class对象
        Class<?> cls = People.class;

        // 取得有参构造
        Constructor<?> constructor = cls.getDeclaredConstructor(String.class);

        // 创建实例化对象
        People people = (People) constructor.newInstance("Leon");

        // 取得指定方法名称的的方法
        Method method = cls.getMethod("setAge", Integer.class);

        // 调用方法
        method.invoke(people, 18);
        System.out.println(people);
    }

四、Filed类:(反射调用类中属性)

1.取得所有类中属性
    Filed[] getFileds() throws SecurityException
    Filed[] getDeclaredFileds() 

2.取得类中指定属性
    getFiled()
    getDeclaredFiled()

3.属性调用:   
    设置属性内容:
        public void set(Object 类的实例化对象:obj,Object 属性值:value);
    取得属性内容:
        public Object get(Object obj)

    getType()// 取得属性类型

猜你喜欢

转载自blog.csdn.net/qq_39026129/article/details/81565520