反射基本知识

  1. 获取对象类型的三种方式
    (1)类.getClass()
    (2)类.class
    (3)Class.forName(全路径)

  2. invoke,setAccessible
    (1)setAccessible,设置是否允许访问,而不是修改原来的访问权限修饰词。
    (2)invoke(Object obj, Object… args),对带有指定参数的指定对象调用由此 Method 对象表示的底层方法。

  3. 重要方法
    (1) 声明方法(包括公共、保护、默认(包)访问的私有构造函数、字段、方法)

    • 声明构造方法

      getDeclaredConstructor( Class < ?> … parameterTypes ),表示的类或接口的指定构造方法。
      Constructor< ?>[] getDeclaredConstructors(),表示的类声明的所有构造方法

    • 声明字段

      getDeclaredField(String name), 表示类或接口指定的已声明字段。
      getDeclaredFields(), 表示类或接口所声明的所有字段。

    • 声明方法

      getDeclaredMethod( String name, Class< ?>… parameterTypes), 表示类或接口的指定已声明方法。
      getDeclaredMethods(),表示类或接口声明的所有方法,包括公共、保护、默认(包)访问和私有方法,但不包括继承的方法。

    (2)公共方法

    • 公共构造函数

      getConstructor(Class< ?>… parameterTypes),表示类的指定公共构造方法。
      getConstructors(), 表示类的所有公共构造方法。

    • 公共字段

      getField(String name),表示类或接口的指定公共成员字段。
      getFields(),表示类或接口的所有可访问公共字段。

    • 公共方法

      getMethod(String name, Class< ?>… parameterTypes), 表示类或接口的指定公共成员方法。
      getMethods(), 表示类或接口(包括那些由该类或接口声明的以及从超类和超接口继承的那些的类或接口)的公共 member 方法。

    (3)parameterTypes - 参数数组 ,按声明顺序标识构造方法的形参类型

  4. 方法实例

    Person1 p=new Person1("火影",17);
    Class clazz=Person1.class;
    //得到类名
    System.out.println(clazz.getName());
    

    (1)访问私有方法(正确方法)

    //getDeclaredMethod(),对象所表示的类或接口的指定【已声明方法】
        Method method=clazz.getDeclaredMethod("test");//访问私有方法需要设置,否则报异常
        method.setAccessible(true);
        method.invoke(p);
    

    (2)访问私有方法(错误方法)

    //getMethod(),它反映此 Class 对象所表示的类或接口的指定【公共成员方法】      
        Method method=clazz.getMethod("test");
        method.setAccessible(true);//不起作用,报异常
        method.invoke(p);
    

    (3)访问公共方法

    Method method1=clazz.getMethod("getName");
    method1.invoke(p);
    

猜你喜欢

转载自blog.csdn.net/OpenWorld1/article/details/52985848